javascript数组映射方法中的break语句 [英] Break statement in javascript array map method
问题描述
可能重复:
如何短路Array.forEach就像叫断点?
有没有办法可以在满足条件后突破数组映射方法?我尝试了以下引发非法中断语句错误。
这是我提出的一些随机示例。
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.
var myArray = [22,34,5,67,99,0];
var hasValueLessThanTen = false;
myArray.map(function (value){
if(value<10){
hasValueLessThanTen = true;
break;
}
}
);
我们可以使用来执行
循环,但是我想知道我们是否可以使用 map
方法完成同样的工作?
We can do using for
loops, but I wanted to know whether we can accomplish the same using map
method ?
推荐答案
使用内置的 数组是不可能的。 prototype.map
。但是,如果您不打算代替 -loop。 docs / JavaScript / Reference / Global_Objects / Array / map> map
任何值:
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:
var hasValueLessThanTen = false;
for (var i = 0; i < myArray.length; i++) {
if (myArray[i] < 10) {
hasValueLessThanTen = true;
break;
}
}
或者,如所示@RobW
,使用 数组.prototype.some
测试是否存在至少一个小于10的元素。当找到与您的函数匹配的元素时,它将停止循环:
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:
var hasValueLessThanTen = myArray.some(function (val) {
return val < 10;
});
这篇关于javascript数组映射方法中的break语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!