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()我们期望的结果是:
3 2 1 end
但是实际上会输出:
end 1 2 3JavaScript中的forEach()方法是一个同步方法,它不支持处理异步函数。如果你在forEach中执行了异步函数,forEach()无法等待异步函数完成,它会继续执行下一项。这意味着如果在forEach()中使用异步函数,无法保证异步任务的执行顺序。
const arr = [1, 2, 3, 4, 5]; // 堆代码 duidaima.com 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] });由于我们在异步函数中使用了await关键字,map()方法会等待异步函数完成并返回结果,因此我们可以正确地处理异步函数。
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();原因二:无法捕获异步函数中的错误
let arr = [1,2,3,4] arr.forEach((item, index) => { console.log(item); // 1 2 3 4 index++; });原因五: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对象的属性。微信搜索公众号:架构师指南,回复:架构师 领取资料 。
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) // 使用bind()方法绑定函数的作用域 ); }, }; obj.printFriends();在这个例子中,我们使用bind()方法来绑定函数的作用域,将该函数的作用域绑定到obj对象上。运行代码后,输出结果为:
Alice is friends with Bob Alice is friends with Charlie Alice is friends with Dave通过使用bind()方法来绑定函数的作用域,我们可以正确地访问obj对象的属性。
// 跳过未初始化的值 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') { // 当到达包含值 `two` 的项时,整个数组的第一个项被移除了 // 这导致所有剩下的项上移一个位置。因为元素 `four` 正位于在数组更前的位置,所以 `three` 会被跳过。 words.shift(); //'one' 将从数组中删除 } }); // one // two // four console.log(words); // ['two', 'three', 'four']原因八:forEach使用不会改变原数组
// 例子一 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] // 例子二 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}]好了,我还是使用for...of去替代forEach吧