js foreach 不能中断的现象及理解
2020-12-17 11:33
标签:code exception nbsp wrong 理解 prototype oop ret star 下例为一个js的foreach操作,看打印的结果,return是无法中断foreach处理的。 结果: foreach就是用来一次遍历完数组左右元素的,如果有中断操作可以使用普通的for循环。 MDN上是这么解释的: js foreach 不能中断的现象及理解 标签:code exception nbsp wrong 理解 prototype oop ret star 原文地址:https://www.cnblogs.com/silenceshining/p/14071512.html现象:
var testArray = [1, 2, 3, 4, 5];
testArray.forEach(element => {
if (element == 3) {
return;
}
console.log(element);
});
1
2
4
5
理解:
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 不能中断的现象及理解
文章链接:http://soscw.com/index.php/essay/36840.html