八個理由告訴你,請停止使用 forEach 函數
1.不支持處理異步函數
async function test() {
let arr = [3, 2, 1]
arr.forEach(async item => {
const res = await mockSync(item)
console.log(res)
})
console.log('end')
}
function mockSync(x) {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(x)
}, 1000 * x)
})
}
test()
Desired result:
3
2
1
end
Actual results:
end
1
2
3
JavaScript 中的 forEach() 方法是一個同步方法,它不支持處理異步函數。
如果在forEach中執行了一個異步函數,forEach()不能等待異步函數完成,它會繼續執行下一項。 這意味著如果在 forEach() 中使用異步函數,則無法保證異步任務的執行順序。
替代 forEach
1.1 使用 map(), filter(), reduce()
他們支持在函數中返回 Promise,并會等待所有 Promise 完成。
使用map()和Promise.all()處理異步函數的示例代碼如下:
const arr = [1, 2, 3, 4, 5];
async function asyncFunction(num) {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(num * 2);
}, 1000);
});
}
const promises = arr.map(async (num) => {
const result = await asyncFunction(num);
return result;
});
Promise.all(promises).then((results) => {
console.log(results); // [2, 4, 6, 8, 10]
});
由于我們在async函數中使用了await關鍵字,map()方法會等待async函數完成并返回結果,以便我們正確處理async函數。
1.2 使用for循環
const arr = [1, 2, 3, 4, 5];
async function asyncFunction(num) {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(num * 2);
}, 1000);
});
}
async function processArray() {
const results = [];
for (let i = 0; i < arr.length; i++) {
const result = await asyncFunction(arr[i]);
results.push(result);
}
console.log(results); // [2, 4, 6, 8, 10]
}
processArray();
2.無法捕獲異步函數中的錯誤
如果異步函數在執行時拋出錯誤,則 forEach() 無法捕獲該錯誤。 這意味著即使 async 函數發生錯誤,forEach() 也會繼續執行。
3. 除了拋出異常外,沒有辦法中止或跳出 forEach() 循環
forEach() 方法不支持使用 break 或 continue 語句來中斷循環或跳過項目。 如果需要跳出循環或跳過某個項目,則應使用 for 循環或其他支持 break 或 continue 語句的方法。
4.forEach刪除自己的元素,索引無法重置
在forEach中,我們無法控制index的值,它會無意識地增加,直到大于數組長度,跳出循環。 因此,也不可能通過刪除自身來重置索引。
讓我們看一個簡單的例子:
let arr = [1,2,3,4]
arr.forEach((item, index) => {
console.log(item); // 1 2 3 4
index++;
});
5.這指向問題
在 forEach() 方法中,this 關鍵字引用調用該方法的對象。 但是,當使用普通函數或箭頭函數作為參數時,this 關鍵字的作用域可能會導致問題。 在箭頭函數中,this 關鍵字引用定義該函數的對象。
在普通函數中,this 關鍵字指的是調用該函數的對象。 如果需要保證this關鍵字的作用域是正確的,可以使用bind()方法綁定函數的作用域。
以下是 forEach() 方法中 this 關鍵字范圍問題的示例:
const obj = {
name: "Alice",
friends: ["Bob", "Charlie", "Dave"],
printFriends: function () {
this.friends.forEach(function (friend) {
console.log(this.name + " is friends with " + friend);
});
},
};
obj.printFriends();
在這個例子中,我們定義了一個名為 obj 的對象,它有一個 printFriends() 方法。
在 printFriends() 方法中,我們使用 forEach() 方法遍歷 friends 數組,并使用普通函數打印每個朋友的名字和 obj 對象的 name 屬性。
但是,當我們運行這段代碼時,輸出是:
undefined is friends with Bob
undefined is friends with Charlie
undefined is friends with Dave
這是因為,在forEach()方法中使用普通函數時,函數的作用域不是調用printFriends()方法的對象,而是全局作用域。
因此,無法在該函數中訪問 obj 對象的屬性。
要解決這個問題,可以使用bind()方法綁定函數作用域,或者使用箭頭函數定義回調函數。 下面是使用 bind() 方法解決問題的代碼示例:
const obj = {
name: "Alice",
friends: ["Bob", "Charlie", "Dave"],
printFriends: function () {
this.friends.forEach(
function (friend) {
console.log(this.name + " is friends with " + friend);
}.bind(this)
);
},
};
obj.printFriends();
在本例中,我們使用bind()方法綁定函數作用域,將函數作用域綁定到obj對象上。 運行代碼后,輸出為:
Alice is friends with Bob
Alice is friends with Charlie
Alice is friends with Dave
通過使用bind()方法綁定函數作用域,我們可以正確訪問obj對象的屬性。
另一種解決方法是使用箭頭函數。 由于箭頭函數沒有自己的 this,它繼承了它所在作用域的 this。因此,在箭頭函數中,this 關鍵字指的是定義該函數的對象。
6、forEach的性能低于for循環
for:for循環沒有額外的函數調用棧和上下文,所以它的實現最簡單。
forEach:對于forEach,其函數簽名包含參數和上下文,因此性能會低于for循環。
7.刪除或未初始化的項目將被跳過
const array = [1, 2, /* empty */, 4];
let num = 0;
array.forEach((ele) => {
console.log(ele);
num++;
});
console.log("num:",num);
// 1
// 2
// 4
// num: 3
const words = ['one', 'two', 'three', 'four'];
words.forEach((word) => {
console.log(word);
if (word === 'two') {
words.shift();
}
}); // one // two // four
console.log(words); // ['two', 'three', 'four']
8. forEach的使用不會改變原來的數組
調用 forEach() 時,它不會更改原始數組,即調用它的數組。 但是那個對象可能會被傳入的回調函數改變。
// 1
const array = [1, 2, 3, 4];
array.forEach(ele => { ele = ele * 3 })
console.log(array); // [1,2,3,4]
const numArr = [33,4,55];
numArr.forEach((ele, index, arr) => {
if (ele === 33) {
arr[index] = 999
}
})
console.log(numArr); // [999, 4, 55]
// 2
const changeItemArr = [{
name: 'wxw',
age: 22
}, {
name: 'wxw2',
age: 33
}]
changeItemArr.forEach(ele => {
if (ele.name === 'wxw2') {
ele = {
name: 'change',
age: 77
}
}
})
console.log(changeItemArr); // [{name: "wxw", age: 22},{name: "wxw2", age: 33}]
const allChangeArr = [{ name: 'wxw', age: 22}, { name: 'wxw2', age: 33}]
allChangeArr.forEach((ele, index, arr) => {
if (ele.name === 'wxw2') {
arr[index] = {
name: 'change',
age: 77
}
}
})
console.log(allChangeArr); // // [{name: "wxw", age: 22},{name: "change", age: 77}]
寫在最后
以上就是我今天想與您分享的8個關于不要再隨意使用ForEach的函數的理由。