[1,2,3].forEach(function(el) {
if(el === 1) break;
});
How can I do this using the new forEach
method in JavaScript? I've tried return;
, return false;
and break
. break
crashes and return
does nothing but continue iteration.
[1,2,3].forEach(function(el) {
if(el === 1) break;
});
How can I do this using the new forEach
method in JavaScript? I've tried return;
, return false;
and break
. break
crashes and return
does nothing but continue iteration.
Consider to use
jquery
'seach
method, since it allows to return false inside callback function:Lodash libraries also provides
takeWhile
method that can be chained with map/reduce/fold etc:From your code example, it looks like
Array.prototype.find
is what you are looking for: Array.prototype.find() and Array.prototype.findIndex()Quoting from the MDN documentation of
Array.prototype.forEach()
:For your code (in the question), as suggested by @bobince, use
Array.prototype.some()
instead. It suits very well to your usecase.Found this solution on another site. You can wrap the forEach in a try / catch scenario.
More details here: http://dean.edwards.name/weblog/2006/07/enum/