短路Array.forEach就像调用break [英] Short circuit Array.forEach like calling break
问题描述
[1,2,3].forEach(function(el) {
if(el === 1) break;
});
如何使用新的 forEach
JavaScript中的方法?我试过 return;
,返回false;
和 break
。 中断
崩溃和返回
除了继续迭代之外什么都不做。
How can I do this using the new forEach
method in JavaScript? I've tried return;
, return false;
and break
. break
crashes and return
does nothing but continue iteration.
推荐答案
forEach
中没有内置的中断
的能力。要中断执行,你必须抛出某种异常。例如。
There's no built-in ability to break
in forEach
. To interrupt execution you would have to throw an exception of some sort. eg.
var BreakException = {};
try {
[1, 2, 3].forEach(function(el) {
console.log(el);
if (el === 2) throw BreakException;
});
} catch (e) {
if (e !== BreakException) throw e;
}
JavaScript异常并不是非常漂亮。如果你真的需要 break
,那么传统的 for
循环可能更合适。
JavaScript exceptions aren't terribly pretty. A traditional for
loop might be more appropriate if you really need to break
inside it.
相反,请使用 Array#some
:
Instead, use Array#some
:
[1, 2, 3].some(function(el) {
console.log(el);
return el === 2;
});
这是因为 some
返回 true
只要以数组顺序执行的任何回调,返回 true
,短路其余的执行。
This works because some
returns true
as soon as any of the callbacks, executed in array order, return true
, short-circuiting the execution of the rest.
一些
,其反向 每个
(将停在返回false
)和 forEach
是所有ECMAScript第五版方法,需要在缺少它们的浏览器上添加到 Array.prototype
。
some
, its inverse every
(which will stop on a return false
), and forEach
are all ECMAScript Fifth Edition methods which will need to be added to the Array.prototype
on browsers where they're missing.
这篇关于短路Array.forEach就像调用break的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!