加入收藏 | 设为首页 | 会员中心 | 我要投稿 济源站长网 (https://www.0391zz.cn/)- 数据工具、数据仓库、行业智能、CDN、运营!
当前位置: 首页 > 综合聚焦 > 编程要点 > 语言 > 正文

forEach能否跳出循环?一文带你搞懂

发布时间:2022-02-19 13:48:44 所属栏目:语言 来源:互联网
导读:今天给大家分享一道JavaScript的面试题,这道问题可是难道不少人呢。JS中我们经常会使用foreach这个方法来遍历数组,那么forEach能否跳出循环?如果能,forEach如何跳出循环?下面我们一起来探讨一下。 forEach使用说明 参考:https://developer.mozilla.org/e
      今天给大家分享一道JavaScript的面试题,这道问题可是难道不少人呢。JS中我们经常会使用foreach这个方法来遍历数组,那么forEach能否跳出循环?如果能,forEach如何跳出循环?下面我们一起来探讨一下。
 
    forEach使用说明
    参考:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach?v=example
 
arr.forEach(function callback(currentValue, index, array) {
    //your iterator
}[, thisArg]);
currentValue --- 当前处理的元素
index --- 当前处理元素的索引
array ---forEach应用的数组
    有一段提示写到了在forEach中break和return的用法。原文如下:
 
There is no way to stop or break a forEach()loop other than by throwing an exception. If you need such behavior, theforEach()method is the wrong tool. Use a plain loop instead. If you are testing the array elements for a predicate and need a Boolean return value, you can useevery() or
some() instead. If available, the new methodsfind() or findIndex() can be used for early termination upon true predicates as well.
 
    意思就是说在forEach中使用break和return是错误的,如果希望使用break或者return请使用every或者some函数。
    那么回到标题,首先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()
    根据不同的业务场景,选择使用对应的工具函数来更有效地处理业务逻辑,至于forEach,我想就从此相忘于江湖吧。

(编辑:济源站长网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    热点阅读