Javascript (ECMAscript) has supported the Array.prototype.forEach method since version 1.6 (ECMAscript edition 3, 2005). Thus, quite a few browsers already support this method, and it is incredibly fast compared to the jQuery $.each() method for example.
(In fact, it surpasses all implementations, regardless of which Javascript library)
Compared to jQuery, it is about 60-70% faster. Try it for yourself: forEach vs. jQuery on JSPerf.
The only drawback I have used so far is that I cannot figure out how early to break the iteration. Like for , while and do-while have a break statement, jQuerys .each() supports return false to break the loop.
I looked at the specifications of ECMAScript Edition 5 (the last thing I found), but they do not mention the early breakthrough of this cycle.
So the question is, can Mr. Douglas Crockford call this design error ?
Am I missing something and can I break such a loop early?
Edit
Thanks for the answers so far. I think that since no one came up with a βnativeβ solution, there really is no implementation for this (maybe a function?). In any case, I do not like the proposed methods, so I cheated a little and finally found the one I like (at least better). It 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 the "real" production code. I was looking for a good way to look for css3 conversion properties, and I got lost in ecma5 specifications and weird Javascript forums :-)
So, you can pass the array object as the third parameter to the .forEach . I create a copy from the original array by calling slice(0) and setting its .length property to 0 as soon as I found what I was looking for. It works well.
If someone comes up with a better solution, I will edit this, of course.