温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

JavaScript中可以使用forEach跳出循环吗

发布时间:2021-06-11 18:21:57 来源:亿速云 阅读:252 作者:Leah 栏目:开发技术

这篇文章给大家介绍JavaScript中可以使用forEach跳出循环吗,内容非常详细,感兴趣的小伙伴们可以参考借鉴,希望对大家能有所帮助。

forEach使用说明

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()

关于JavaScript中可以使用forEach跳出循环吗就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI