[1,2,3].forEach(function(el) {
if(el === 1) break;
});
How can I do this using the new forEach method of JS?
[1,2,3].forEach(function(el) {
if(el === 1) break;
});
How can I do this using the new forEach method of JS?
There's no built-in ability to break in forEach. To interrupt execution you would have to throw an exception of some sort. eg.
var BreakException= {};
try {
[1,2,3].forEach(function(el) {
if(el === 1) throw BreakException;
});
} catch(e) {
if (e!==BreakException) throw e;
}
JavaScript exceptions aren't terribly pretty. An traditional for loop may be more appropriate if you really need to break inside it. Or, you could rely on a side-effect of Array#some:
[1,2,3].some(function(el) {
return el === 1;
});
This works because some returns true as soon as any of the callbacks, executed in array order, return true, short-circuiting the execution of the rest.
some, its inverse every (which will stop on a return false), and forEach are all ECMAScript Fifth Edition methods which will need to be added to the Array.prototype on browsers where they're missing.
Also you could use jQuery.each(function(element, index) {}); as soon as you can use return false; inside
Found this solution on another site. You can wrap the forEach in a try / catch scenario.
if(typeof StopIteration == "undefined") {
StopIteration = new Error("StopIteration");
}
try {
[1,2,3].forEach(function(el){
alert(el);
if(el === 1) throw StopIteration;
});
} catch(error) { if(error != StopIteration) throw error; }
More details here: http://dean.edwards.name/weblog/2006/07/enum/
Maybe I'm missing something here, but it looks like you might be falling victim of the shiny-new-toy disease. Why not just use a standard for/break? forEach is designed to be run against each element, hence the name. It's not called forSome ;-)
-Oisin