Javascript javascript数组映射方法中的break语句
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12260529/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Break statement in javascript array map method
提问by Mudassir Ali
Possible Duplicate:
How to short circuit Array.forEach like calling break?
Is there a way so that I can break out of array map method after my condition is met ? I tried the following which throws "Illegal Break Statement" Error.
This is some random example I came up with.
有没有办法在满足我的条件后突破数组映射方法?我尝试了以下抛出"Illegal Break Statement" Error.
这是我想出的一些随机示例。
var myArray = [22,34,5,67,99,0];
var hasValueLessThanTen = false;
myArray.map(function (value){
if(value<10){
hasValueLessThanTen = true;
break;
}
}
);
We can do using for
loops, but I wanted to know whether we can accomplish the same using map
method ?
我们可以使用for
循环,但我想知道我们是否可以使用map
方法完成相同的操作?
回答by Jo?o Silva
That's not possible using the built-in Array.prototype.map
. However, you could use a simple for
-loop instead, if you do not intend to map
any values:
使用内置的Array.prototype.map
. 但是,for
如果您不打算使用map
任何值,则可以改用简单的-loop :
var hasValueLessThanTen = false;
for (var i = 0; i < myArray.length; i++) {
if (myArray[i] < 10) {
hasValueLessThanTen = true;
break;
}
}
Or, as suggested by @RobW
, use Array.prototype.some
to test if there exists at least one element that is less than 10. It will stop looping when some element that matches your function is found:
或者,如 所建议的@RobW
,用于Array.prototype.some
测试是否存在至少一个小于 10 的元素。当找到与您的函数匹配的某个元素时,它将停止循环:
var hasValueLessThanTen = myArray.some(function (val) {
return val < 10;
});