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 cannot break a
forEach
in underscore, as it emulates EcmaScript 5 native behaviour.Like the other answers, it's impossible. Here is the comment about breaker in underscore underscore issue #21
You can have a look to
_.some
instead of_.each
._.some
stops traversing the list once a predicate is true. Result(s) can be stored in an external variable.See http://underscorejs.org/#some
Update:
You can actually "break" by throwing an error inside and catching it outside: something like this:
This obviously has some implications regarding any other exceptions that your code trigger in the loop, so use with caution!
You can't break from the
each
method—it emulates the nativeforEach
method's behavior, and the nativeforEach
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:
In other words, you could do something convoluted like this (link to JSFiddle):
This will alert
1
through3
, 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 itevery
, but as that link mentions, they also provide an alias calledall
.http://underscorejs.org/#each