八個(gè)理由告訴你,請停止使用 forEach 函數(shù)
1.不支持處理異步函數(shù)
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() 方法是一個(gè)同步方法,它不支持處理異步函數(shù)。
如果在forEach中執(zhí)行了一個(gè)異步函數(shù),forEach()不能等待異步函數(shù)完成,它會繼續(xù)執(zhí)行下一項(xiàng)。 這意味著如果在 forEach() 中使用異步函數(shù),則無法保證異步任務(wù)的執(zhí)行順序。
替代 forEach
1.1 使用 map(), filter(), reduce()
他們支持在函數(shù)中返回 Promise,并會等待所有 Promise 完成。
使用map()和Promise.all()處理異步函數(shù)的示例代碼如下:
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函數(shù)中使用了await關(guān)鍵字,map()方法會等待async函數(shù)完成并返回結(jié)果,以便我們正確處理async函數(shù)。
1.2 使用for循環(huán)
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.無法捕獲異步函數(shù)中的錯(cuò)誤
如果異步函數(shù)在執(zhí)行時(shí)拋出錯(cuò)誤,則 forEach() 無法捕獲該錯(cuò)誤。 這意味著即使 async 函數(shù)發(fā)生錯(cuò)誤,forEach() 也會繼續(xù)執(zhí)行。
3. 除了拋出異常外,沒有辦法中止或跳出 forEach() 循環(huán)
forEach() 方法不支持使用 break 或 continue 語句來中斷循環(huán)或跳過項(xiàng)目。 如果需要跳出循環(huán)或跳過某個(gè)項(xiàng)目,則應(yīng)使用 for 循環(huán)或其他支持 break 或 continue 語句的方法。
4.forEach刪除自己的元素,索引無法重置
在forEach中,我們無法控制index的值,它會無意識地增加,直到大于數(shù)組長度,跳出循環(huán)。 因此,也不可能通過刪除自身來重置索引。
讓我們看一個(gè)簡單的例子:
let arr = [1,2,3,4]
arr.forEach((item, index) => {
console.log(item); // 1 2 3 4
index++;
});
5.這指向問題
在 forEach() 方法中,this 關(guān)鍵字引用調(diào)用該方法的對象。 但是,當(dāng)使用普通函數(shù)或箭頭函數(shù)作為參數(shù)時(shí),this 關(guān)鍵字的作用域可能會導(dǎo)致問題。 在箭頭函數(shù)中,this 關(guān)鍵字引用定義該函數(shù)的對象。
在普通函數(shù)中,this 關(guān)鍵字指的是調(diào)用該函數(shù)的對象。 如果需要保證this關(guān)鍵字的作用域是正確的,可以使用bind()方法綁定函數(shù)的作用域。
以下是 forEach() 方法中 this 關(guān)鍵字范圍問題的示例:
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();
在這個(gè)例子中,我們定義了一個(gè)名為 obj 的對象,它有一個(gè) printFriends() 方法。
在 printFriends() 方法中,我們使用 forEach() 方法遍歷 friends 數(shù)組,并使用普通函數(shù)打印每個(gè)朋友的名字和 obj 對象的 name 屬性。
但是,當(dāng)我們運(yùn)行這段代碼時(shí),輸出是:
undefined is friends with Bob
undefined is friends with Charlie
undefined is friends with Dave
這是因?yàn)椋趂orEach()方法中使用普通函數(shù)時(shí),函數(shù)的作用域不是調(diào)用printFriends()方法的對象,而是全局作用域。
因此,無法在該函數(shù)中訪問 obj 對象的屬性。
要解決這個(gè)問題,可以使用bind()方法綁定函數(shù)作用域,或者使用箭頭函數(shù)定義回調(diào)函數(shù)。 下面是使用 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()方法綁定函數(shù)作用域,將函數(shù)作用域綁定到obj對象上。 運(yùn)行代碼后,輸出為:
Alice is friends with Bob
Alice is friends with Charlie
Alice is friends with Dave
通過使用bind()方法綁定函數(shù)作用域,我們可以正確訪問obj對象的屬性。
另一種解決方法是使用箭頭函數(shù)。 由于箭頭函數(shù)沒有自己的 this,它繼承了它所在作用域的 this。因此,在箭頭函數(shù)中,this 關(guān)鍵字指的是定義該函數(shù)的對象。
6、forEach的性能低于for循環(huán)
for:for循環(huán)沒有額外的函數(shù)調(diào)用棧和上下文,所以它的實(shí)現(xiàn)最簡單。
forEach:對于forEach,其函數(shù)簽名包含參數(shù)和上下文,因此性能會低于for循環(huán)。
7.刪除或未初始化的項(xiàng)目將被跳過
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的使用不會改變原來的數(shù)組
調(diào)用 forEach() 時(shí),它不會更改原始數(shù)組,即調(diào)用它的數(shù)組。 但是那個(gè)對象可能會被傳入的回調(diào)函數(shù)改變。
// 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個(gè)關(guān)于不要再隨意使用ForEach的函數(shù)的理由。