Hi Folks,
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.