放弃使用forEach的理由

发布时间 2023-06-25 10:48:23作者: 看风景就

js中Array的forEach有如下缺点

1. 不支持异步,内部用await无效
2. 无法中断,不支持break,continue
3. 跳过已删除和未初始化的项
4. 不能修改数组项

替代方案

1. map()、filter()、reduce()支持异步,for循环和for of都支持异步

const promises = arr.map(async (num) => {
    const result = await asyncFunction(num);
    return result;
});
  
Promise.all(promises).then((results) => {
    console.log(results);
});

2. for循环和for...of都支持中断

for (let item of data) {
    if (xxx) break;
}

3. for循环和for...of都不会跳过已删除和未初始化的项

4. for循环和for...of修改数组项,或者 forEach中用数组修改

//利用forEach的index,用数组直接修改
arr.forEach((ele, index, arr) => {
    if (xxx) {
        arr[index] = xxx
    }
})