2016-07-31 32 views
1

我有一個名爲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} 
     ] 

問題

我具有相同的陣列ARR1稱爲 'ARR2'。我想要做的是將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

爲什麼你不只是用我聽不懂第二個數組直接。試圖在它們之間交叉引用的期望好處是什麼? – nnnnnn

+0

爲了簡單起見,在示例中。它在代碼中被映射出來,但爲了引用目的,數組必須是分開的。 –

回答

1

我希望我能正確理解你的問題。請在代碼部分閱讀我的評論。

我不得不修改你的源代碼,所以我能夠爲你創建一個小提琴。

HTML:我改變了點擊事件,並刪除CSS類,這不是可用

<button type="button" role="menuitem" onclick="clickNext();">Next</button> 

SAMPE陣列: 它們含有無效對象:我改變了α,β,探戈,..一個屬性。您也可以將它們定義爲值..這不應該的問題:

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); 
} 

小提琴:https://jsfiddle.net/k50y8pp5/