2016-04-02 64 views
3

我有以下方面:接頭上forEach循環不正常

https://jsfiddle.net/eqntaqbt/2/

obj.forEach(function(user, index){ 
    var userName = user.name; 
    console.log(index, userName); 

    if(index === 5 || index === 2){ 
    obj.splice(index, 1); 
    } 
}); 

我使用的是forEach環和splice以去除obj陣列上5位置和2的項目。但由於某種原因,它不能正常工作。

我在做什麼錯?

+0

'user.index' ..? – Rayon

+0

它工作正常..沒有看到記錄的用戶名,請檢查你的filddle中最後記錄的數組。 –

+0

剛剛更新了問題 – gespinha

回答

5

你的代碼是拼接而循環。拼接元素即使不存在也可以訪問。這導致未定義的元素。

您可以考慮Array#filter

var obj = [{ "index": 0, "name": "Odonnell Noble", "gender": "male", "company": "DIGIQUE", "eail": "[email protected]" }, { "index": 1, "name": "Marie Oneal", "gender": "female", "company": "CANOPOLY", "email": "[email protected]" }, { "index": 2, "name": "Adrienne Marsh", "gender": "female", "company": "XOGGLE", "email": "[email protected]" }, { "index": 3, "name": "Goff Mullins", "gender": "male", "company": "ENDIPIN", "email": "[email protected]" }, { "index": 4, "name": "Lucile Finley", "gender": "female", "company": "AQUASSEUR", "email": "[email protected]" }, { "index": 5, "name": "Pitts Mcpherson", "gender": "male", "company": "QUARX", "email": "[email protected]" }]; 
 

 
obj = obj.filter(function (user, index) { 
 
    return (user.index !== 5 && user.index !== 2); 
 
}); 
 

 
document.write('<pre>' + JSON.stringify(obj, 0, 4) + '</pre>');

+0

爲什麼他的代碼不工作? Plz解釋說。我認爲反向while循環可能是解決它的好選擇。 –

+0

謝謝,它像一個魅力:) – gespinha

1

Array#forEach

通過的forEach處理的元素的範圍()在第一 調用回調的之前設置。在對forEach()的調用開始後 後追加到數組的元素將不會被回調訪問。如果數組中現有元素的 值發生更改,則傳遞給 的值將是forEach()訪問它們時的值; 被訪問前被刪除的元素未被訪問

obj.forEach(function(user, index){ 
    var userName = user.name; 
    //console.log(index, userName); 

    if(user.index === 5 || user.index === 2){ 
    this.splice(index, 1); 

    } 
}.bind(obj)); 

這裏是工作fiddle

0

的forEach被而是意味着所謂的副作用。

你的代碼存在的問題是,你在迭代它時正在改變數組。因此,如果您刪除一個項目,則陣列的所有其他索引將立即重新分配。這就是爲什麼刪除一個項目後,進一步刪除不會做所需的事情(在所需的位置)。

因此forEach對於影響實際數組之外的事物是很好的,這是迭代的。

這對於一個稱爲過濾器的函數來說是一個完美的用例,因爲實際上,您對列表做了什麼:你想過濾掉一些項目。

array = array.filter(function(item, index) { 
    return (index !== 5 && index !== 2) 
} 

過濾函數除了函數作爲參數,其本身將被調用的數組中的每個項目。如果該函數對某個項目返回true,則會保留 - 否則將被刪除。這就是爲什麼邏輯表達式必須在這裏稍微改變的原因:它看起來像這樣:保持不是索引5而不是索引2的項目。這些真或假返回函數稱爲謂詞。

如果您想過濾掉更多的索引,該怎麼辦?使用locical運算符的表達式變得很快。

您可以在索引列表上使用數組方法indexOf,每次將數組的當前索引傳遞給索引。如果它不在裏面,它會返回一個位置或-1。在後面的情況下,您希望將該項目保留在數組中。

array = array.filter(function(item, current_index) { 
    return ([2, 5].indexOf(current_index) === -1) 
} 

此外,你可以包裝在一個函數:

function removeIndices(array, indices) { 
    return array.filter(function(item, current_index) { 
     return (indices.indexOf(current_index) === -1) 
    }) 
} 

最後:

array = removeIndices(array, [2, 5]);