You can't break from the each
method—it emulates the native forEach
method's behavior, and the native forEach
doesn't provide to escape the loop (other than throwing an exception).
However, all hope is not lost! You can use the Array.every
method. :)
From that link:
every
executes the provided callback
function once for each element present in the array until it finds one where callback
returns a false value. If such an element is found, the every
method immediately returns false.
In other words, you could do something convoluted like this (link to JSFiddle):
[1, 2, 3, 4].every(function(n) {
alert(n);
return n !== 3;
});
This will alert 1
through 3
, and then "break" out of the loop.
You're using underscore.js, so you'll be pleased to learn that it does provide an every
method—they call it every
, but as that link mentions, they also provide an alias called all
.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…