There's no built-in ability to break
in forEach
.
(没有内置的能力可以break
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 exceptions aren't terribly pretty.
(JavaScript异常不是很漂亮。)
A traditional for
loop might be more appropriate if you really need to break
inside it. (传统for
,如果你真的需要循环可能更适合break
里面。)
Instead, use Array#some
:
(而是使用Array#some
:)
[1, 2, 3].some(function(el) { console.log(el); return el === 2; });
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.
(之所以true
是因为some
以数组顺序执行的回调一旦返回true
,就会使true
短路,从而使其余的执行短路。)
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.
(some
,其every
相反(将在return false
停止),以及forEach
都是ECMAScript Fifth Edition方法,需要在缺少它们的浏览器上将它们添加到Array.prototype
。)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…