Javascript (ECMAscript) supports the Array.prototype.forEach
method since version 1.6 (ECMAscript edition 3, 2005). So quite a lot of browser already support that method and it's incredibly fast in comparison to jQuery's $.each()
method for instance.
(Actually it beats all implementations, regardless which Javascript library)
In comparison to jQuery it's about 60-70% faster. Try it yourself on forEach vs. jQuery on JSPerf.
The only downside I have so far using it is, I can't figure a way to break the iteration early. Like for
, while
and do-while
have a break
statement, jQuerys .each()
supports the return false
to break the loop.
I looked into the ECMAScript Edition 5 Specifications (the latest I found), but they don't mention an early break from that loop.
So, question, would Mr. Douglas Crockford call this a design error
?
Am I missing something and it is possible to break such a loop early?
Edit
Thanks for the answers so far. I guess since nobody came up with a "native" solution, there really is no implementation for that (maybe a feature?). Anyway, I don't really like the suggested methods so I fooled around a little and finally found one I do like (at least, better). Looks like:
var div = document.createElement('div'),
divStyle = div.style,
support = jQuery.support,
arr = ['MozTransform', 'WebkitTransform', 'OTransform'];
arr.slice(0).forEach(function(v,i,a){
if(divStyle[v] === ''){
support.transform = v;
a.length = 0;
}
});
This is "real" production code. I looked for a nice way to lookup the css3 transform properties and I got lost in ecma5 specs & weird Javascript forums :-)
So, you may pass the array object itself as third parameter into the .forEach
callback. I create a copy from the original array, calling slice(0)
and set its .length
property to 0 as soon as I found what I'm looking for. Works quite well.
If someone comes up with a better solution I'll edit this of course.
Well, you could use every
instead. The function is designed to return true
if the provided callback function returns true
(truthy) for every element in the array, and false
otherwise. Key point here is that once the callback function returns a falsly value, every
immediatly returns false
without iterating over the rest of the array. So just ignore the return value, and treat every
as if it were forEach
.
[1, 2, 3, 4, 5].every(function(e) {
alert(e);
if (e > 2) return false; //break
return true;
});
In this example, alert
will only fire 3 times.
Of course the big cavet here is that you must return a truthy value if you want the loop to continue. In fact if you return nothing (undefined) the loop will stop. Alternativly, you could use some
which behaves in the exact opposite manner; immediatly returns true when the callback function returns a truthy value and false if it never does. In this case, return true
would be your "break" statement. Backwards yes, but it saves you from having to return true
simply to have the loop continue.
Now, if you are concerened with performance, I'd recomend just using a normal for
loop, as there is significant overhead incurred when calling functionas that will add up very quickly with larger arrays. Using native functions helps somewhat, but the overhead of repeated calls to user-defined functions still exists and is non-trivial. At least this has been my experience, you should of course do your own testing.
You could throw an error to break out of the iteration:
if (typeof BreakIteration == "undefined") {
BreakIteration = new Error("BreakIteration");
}
try {
[0,1,2,3,4].forEach(function(key, value) {
console.log(key + ': ' + value);
if (value == 3) {
throw BreakIteration;
}
});
} catch (error) {
if (error !== BreakIteration) {
throw error;
}
}
This isn't exactly pretty. I agree -- spec bug.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With