Is one way more efficient? Are there any limitations in one method versus the other? Thanks for any input you guys can give me ;-)
views:
101answers:
2
+6
A:
The Array.prototype.forEach method is part of the ECMAScript 5th Edition Specification, is available on all browsers but not in IE.
I would suggest you to use a simple sequential for loop, IMO is more efficient since forEach needs a callback function, a function will be created starting a closure and you don't need to care about IE.
But if you want to use forEach and all the other new Array.prototype methods such as map, filter, every, some, etc... you can add an implementation for IE, in the pages I linked.
CMS
2010-06-14 23:32:35
just a note: forEach is more efficient on, so far, Opera and Chrome.
unomi
2010-06-15 00:31:56
I find `forEach` lightning fast on Firefox, I've made a simple [performance test](http://jsbin.com/oguho/2), feel free to [play with it](http://jsbin.com/oguho/2/edit).
CMS
2010-06-15 01:33:21
+2
A:
Similar to for each but supported in all browsers
for (var i = 0, myArrayElement; myArrayElement = myArray[i]; i++) {
//now you can just use
// myArrayElement
// instead of
// myArray[i]
}
Just to be aware, I use this when iterating though form collections (ie document.forms[0].elements)
John Hartsock
2010-06-14 23:40:10
Just take note that the loop will be braked prematurely if an array element value is *falsy* (`0`, `null`, `undefined`, `NaN`, an empty string, and of course `false`). Try with `var myArray = [0, 1, 2];`
CMS
2010-06-14 23:43:21
Good Point CMS. Just to be aware I use this when iterating though form collections (ie document.forms[0].elements)
John Hartsock
2010-06-14 23:46:02
@John Hartsock, you should stick the comment you just made in your main reply. Then we can +1 you.
ItzWarty
2010-06-15 00:19:00
`for (var x,i=0; x=data[i++];) {...}` is another way of doing this, but it still has the 'falsy' problem. See also http://stackoverflow.com/questions/2971698/how-to-do-it-more-efficiently/2972364#2972364, see #7 for an example of how to do it without requiring items evaluating to `true`, although it's quite messy :-)
David Morrissey
2010-06-15 01:42:06