Do you think there is a big difference in for...in and for loops? What kind of \"for\" do you prefer to use and why?
Let\'s say we have an array of associative array
Watch out!
If you have several script tags and your're searching an information in tag attributes for example, you have to use .length property with a for loop because it isn't a simple array but an HTMLCollection object.
https://developer.mozilla.org/en/DOM/HTMLCollection
If you use the foreach statement for(var i in yourList) it will return proterties and methods of the HTMLCollection in most browsers!
var scriptTags = document.getElementsByTagName("script");
for(var i = 0; i < scriptTags.length; i++)
alert(i); // Will print all your elements index (you can get src attribute value using scriptTags[i].attributes[0].value)
for(var i in scriptTags)
alert(i); // Will print "length", "item" and "namedItem" in addition to your elements!
Even if getElementsByTagName should return a NodeList, most browser are returning an HTMLCollection: https://developer.mozilla.org/en/DOM/document.getElementsByTagName
Updated answer for 2012 current version of all major browsers - Chrome, Firefox, IE9, Safari and Opera support ES5's native array.forEach.
Unless you have some reason to support IE8 natively (keeping in mind ES5-shim or Chrome frame can be provided to these users, which will provide a proper JS environment), it's cleaner to simply use the language's proper syntax:
myArray.forEach(function(item, index) {
console.log(item, index);
});
Full documentation for array.forEach() is at MDN.
A shorter and best code according to jsperf is
keys = Object.keys(obj);
for (var i = keys.length; i--;){
value = obj[keys[i]];// or other action
}
The two are not the same when the array is sparse.
var array = [0, 1, 2, , , 5];
for (var k in array) {
// Not guaranteed by the language spec to iterate in order.
alert(k); // Outputs 0, 1, 2, 5.
// Behavior when loop body adds to the array is unclear.
}
for (var i = 0; i < array.length; ++i) {
// Iterates in order.
// i is a number, not a string.
alert(i); // Outputs 0, 1, 2, 3, 4, 5
// Behavior when loop body modifies array is clearer.
}
If you really want to speed up your code, what about that?
for( var i=0,j=null; j=array[i++]; foo(j) );
it's kinda of having the while logic within the for statement and it's less redundant. Also firefox has Array.forEach and Array.filter
there are performance differences depending on what kind of loop you use and on what browser.
For instance:
for (var i = myArray.length-1; i >= 0; i--)
is almost twice as fast on some browsers than:
for (var i = 0; i < myArray.length; i++)
However unless your arrays are HUGE or you loop them constantly all are fast enough. I seriously doubt that array looping is a bottleneck in your project (or for any other project for that matter)