forEach是不能使用任何手段跳出循环的,为什么呢?我们知道forEach接收一个函数,它一般有两个参数,第一个是循环的当前元素,第二个是该元素对应的下标,我们手动实现一下:
Array.prototype.myForEach = function (fn) {
    for (let i = 0; i < this.length; i++) {
        fn(this[i], i, this);
    }
}
复制代码

forEach是不是真的这么实现我无从考究,但是以上这个简单的伪代码确实满足forEach的特性,而且也很明显就是不能跳出循环,因为你根本没有办法操作到真正的for循环体。

后来经过查阅文档,发现官方对forEach的定义根本不是我认为的语法糖,它的标准说法是forEach为每个数组元素执行一次你所提供的函数。到这里我的思路逐渐明朗,官方文档也有这么一段话:

除抛出异常之外,没有其他方法可以停止或中断循环。如果您需要这种行为,则该forEach()方法是错误的工具。

使用抛出异常来跳出foreach循环

let arr = [0, 1, "stop", 3, 4];
try {
    arr.forEach(element => {
        if (element === "stop") {
            throw new Error("forEachBreak");
        }
        console.log(element); // 输出 0 1 后面不输出
    });
} catch (e) {
    console.log(e.message); // forEachBreak
};
复制代码

当然,使用try-catch包裹时,当循环体过大性能会随之下降,这是无法避免的,所以抛出异常并不是解决forEach问题的银弹,我们回归到开头写的那段伪代码,我们对它进行一些优化,在真正的for循环中加入对传入函数的判断:

Array.prototype.forEach = function (fn) {
    for (let i = 0; i < this.length; i++) {
        let ret = fn(this[i], i, this);
        if (typeof ret !== "undefined" && (ret == null || ret == false)) break;
    }
}
复制代码

这样的话自然就能根据return值来进行循环跳出啦:

let arr = [0, 1, "stop", 3, 4];

arr.forEach(element => {
    if (element === 'stop') return false
    console.log(element); // 输出 0 1 后面不输出
});

console.log('return即为continue:');
arr.forEach(element => {
    if (element === 'stop') return
    console.log(element); // 0 1 3 4
});
复制代码

文档中还提到forEach需要一个同步函数,也就是说在使用异步函数或Promise作为回调时会发生预期以外的结果,所以forEach还是需要慎用或者不要使用,当然这并不意味着项目开发中要一直用简单的for循环去完成一切事情,我们可以在遍历数组时使用for..of..,在遍历对象时使用for..in..,而官方也在forEach文档下列举了其它一些工具函数:

Array.prototype.find()
Array.prototype.findIndex()
Array.prototype.map()
Array.prototype.filter()
Array.prototype.every()
Array.prototype.some()