今天調試js,其中用到了forEach。發現forEach方法跟預想的不太一樣,去網上一搜找到了這篇。記錄並分享一下。
jQuery 中大家都使用 each,而很少用 for,在 TypeScript 中也有類似的現象,都用 forEach,而很少用 for,但是其實 for 真的挺好用。而 forEach 反而要慎用。
誤用一、用在查找
var arr = [4, 5, 6]; // 各元素值不同
arr.forEach((item) => {
if (item == user.id) {
// do something
}
});
arr.forEach((item) => {
if (item == user.id) {
// do something
}
});
上述代碼大意是想在一個數組中,找到與 id 對應的值,找到后做點事。
其實像上述這種情況下,往往我們需要在找到后 break 的,但是 forEach 不能 break,不管你 return 什么。
誤區二、類似 for 中刪除數組元素
var arr = [4, 5, 6];
arr.forEach((item, index) => {
console.log(item + "x" + index);
if (item > 4) {
arr.splice(index, 1);
}
});
console.log(arr);
arr.forEach((item, index) => {
console.log(item + "x" + index);
if (item > 4) {
arr.splice(index, 1);
}
});
console.log(arr);
結果只循環了 2 次,6 根本就沒有進入循環,原來這個刪除了之后,數組后面的前移了,但是指針還在后移,就漏掉了一個元素。
原文來源:http://www.itpow.com/c/2019/12/11669.asp