js foreach 不能中断的现象及理解

2020-12-17 11:33

阅读:737

标签:code   exception   nbsp   wrong   理解   prototype   oop   ret   star   

现象:

下例为一个js的foreach操作,看打印的结果,return是无法中断foreach处理的。

var testArray = [1, 2, 3, 4, 5];
testArray.forEach(element => {
    if (element == 3) {
        return;
    }
    console.log(element);
});

结果:

1
2
4
5

理解:

foreach就是用来一次遍历完数组左右元素的,如果有中断操作可以使用普通的for循环。

MDN上是这么解释的:

There is no way to stop or break a forEach() loop other than by throwing an exception. 
If you need such behavior, the forEach() method is the wrong tool. Early termination may be accomplished
with: A simple for loop A for...of / for...in loops Array.prototype.every() Array.prototype.some() Array.prototype.find() Array.prototype.findIndex() Array methods: every(), some(), find(), and findIndex() test the array elements with a predicate returning a truthy value to determine if further iteration is required.

 

js foreach 不能中断的现象及理解

标签:code   exception   nbsp   wrong   理解   prototype   oop   ret   star   

原文地址:https://www.cnblogs.com/silenceshining/p/14071512.html


评论


亲,登录后才可以留言!