我有一个名为clickNext()的按钮。只要单击该按钮,它就会在名为“arr1”的数组上递增索引位置(scope.selected)。
<button type="button" class="right-btn col-xs-6" role="menuitem" ng-click="clickNext()">Next</button>
function clickNext()
{
scope.selected = (scope.selected + 1) % length;
}
arr1 = [
{apple: 1 , tango},
{banana: 3, kappa},
{orange:5, alpha},
{apple: 8 , beta},
{grape: 10 , sigma}
]
问题
我有一个名为'arr2'的arr1相同的数组。我要做的是将clickNext()增加到基于 arr2数组而不是arr1数组的下一个索引位置。
现在,clickNext函数仍按arr1数组的顺序递增。例如,如果我点击按钮,它将以橙色开始:5然后移至苹果8等。
arr2 = [
{orange:5, alpha},
{apple: 8 , beta},
{banana: 3, kappa},
{grape: 10 , sigma},
{apple: 1 , tango}
]
我尝试了什么 我完成此任务的过程是使用findIndex()函数并将arr2项与arr1项匹配。这不起作用,但也许我正在构建它错了?
clickNext(){
var oldIndex = filteredToXs(scope.selected);
scope.selected = oldIndex + 1;}
function filteredToXs( filteredIndex ) {
var firstArr = scope.arr1[ filteredIndex ];
var xsIndex = scope.arr2.findIndex( function(item) {
return item.trackingNumber === firstArr.trackingNumber;
} );
if( xsIndex >= 0 ) return xsIndex;
if( xsIndex === -1 ) return 0; // Default value
}
答案 0 :(得分:1)
我希望我能正确理解你的问题。请在代码部分阅读我的评论。
我不得不修改你的来源,所以我能为你创造一个小提琴。
HTML:我更改了点击事件并删除了一个“不可用”的css类
<button type="button" role="menuitem" onclick="clickNext();">Next</button>
Sampe Arrays: 它们包含无效的对象:我将alpha,beta,tango,..更改为属性。您也可以将它们定义为值..这不重要:
var arr1 = [
{ apple: 1, tango: '' },
{ banana: 3, kappa: '' },
{ orange: 5, alpha: '' },
{ apple: 8, beta: '' },
{ grape: 10, sigma: '' }];
var arr2 = [
{ orange: 5, alpha: '' },
{ apple: 8, beta: '' },
{ banana: 3, kappa: '' },
{ grape: 10, sigma: '' },
{ apple: 1, tango: '' }];
代码:
var idx = 0; //save current index of array 2
function clickNext() {
idx++;
//I'm comparing the array objects using a string compare- this only works because you said 'I have an identical array'
//this may cause issues if you're objects are cross-referenced
var find = function(array, obj) { //lookup value from arr2 in arr1
for (var i=0, l=array.length;i<l;i++)
if (JSON.stringify(array[i]) == JSON.stringify(obj)) //adjust this line to your needs
return array[i];
}
var result = find(arr1, arr2[idx])
if (!result)
throw new Error('not found- your arrays are not identical or you run out of index');
console.log(result);
}