美文网首页
forEach 函数的几个缺点

forEach 函数的几个缺点

作者: 刘其瑞 | 来源:发表于2024-06-26 15:43 被阅读0次

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)
    })
}
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. 删除或未初始化的项目将被跳过

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']

6 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}]

相关文章

网友评论

      本文标题:forEach 函数的几个缺点

      本文链接:https://www.haomeiwen.com/subject/oxxscjtx.html