Search

10/13/2013

javascript - How to short circuit Array.forEach like calling break? - Stack Overflow

javascript - How to short circuit Array.forEach like calling break? - Stack Overflow

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. Instead, use 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
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 ;-)

沒有留言: