I’m looking for a way to stop iterations of underscore.js _.each() method, but can’t find the solution. jQuery .each() can break if you do return false.
Is there a way to stop underscore each()?
_([1,2,3]).each(function(v){
if (v==2) return /*what?*/;
})
You can’t break from the
eachmethod—it emulates the nativeforEachmethod’s behavior, and the nativeforEachdoesn’t provide to escape the loop (other than throwing an exception).However, all hope is not lost! You can use the
Array.everymethod. 🙂From that link:
In other words, you could do something convoluted like this (link to JSFiddle):
This will alert
1through3, and then “break” out of the loop.You’re using underscore.js, so you’ll be pleased to learn that it does provide an
everymethod—they call itevery, but as that link mentions, they also provide an alias calledall.