forEach与for区别

406 阅读1分钟

forEach与for区别

  1. for循环可以使用break跳出循环,但forEach不能。
  2. for循环可以控制循环起点(i初始化的数字决定循环的起点),forEach只能默认从索引0开始。
  3. for循环过程中支持修改索引(修改 i),但forEach做不到(底层控制index自增,我们无法左右它)。

使用forEach的注意事项:

  • forEach不支持break
  • forEach中使用return无效
//替代方法
function find(array, num) {
    let _index;
    array.forEach((self, index) => {
        if (self === num) {
            _index = index;
        };
    });
    return _index;
};
  • forEach删除自身元素index不会被重置

forEach结合try...catch()可以跳出循环

try {
    var arr = [1, 2, 3, 4];
    arr.forEach(function (item, index) {
        //跳出条件
        if (item === 3) {
            throw new Error("LoopTerminates");
        }
        //do something
        console.log(item);
    });
} catch (e) {
    if (e.message !== "LoopTerminates") throw e;
};