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
I believe if your array was actually an object you could return using an empty object.
_.({1,2,3,4,5}).each(function(v){
if(v===3) return {};
});
Update:
You can actually "break" by throwing an error inside and catching it outside: something like this:
try{
_([1,2,3]).each(function(v){
if (v==2) throw new Error('break');
});
}catch(e){
if(e.message === 'break'){
//break successful
}
}
This obviously has some implications regarding any other exceptions that your code trigger in the loop, so use with caution!
worked in my case
var arr2 = _.filter(arr, function(item){
if ( item == 3 ) return item;
});
It's also good to note that an each loop cannot be broken out of — to break, use _.find instead.
http://underscorejs.org/#each
You cannot break a forEach
in underscore, as it emulates EcmaScript 5 native behaviour.