What is the difference if I use one of the following to iterate javascript arrays:
for (var i = 0 ; i <abc.length :i++)
or
for (var i in abc.lengh)
Thank you.
What is the difference if I use one of the following to iterate javascript arrays:
for (var i = 0 ; i <abc.length :i++)
or
for (var i in abc.lengh)
Thank you.
For iterating the elements of an array, you should use this form:
var x = [1,2,3,4];
for (var i = 0, len = x.length; i < len; i++) {
// code here to access x[i]
}
For iterating the properties of an object, you should use this:
var house = {size: 3200, bedrooms: 5, garage: 2, color: "white", city: "San Francisco"};
for (var key in house) {
// access each property here as house[key]
}
Though you can sometimes get away with using the second syntax on an array, you are asking for trouble because it will include custom properties that have been added to the array that are not array elements themselves and that can really confuse the code and lead to subtle or not-so-subtle bugs.
The addition of the len
variable in the first syntax is a speed optimization because fetching the length one into a local variable can be significantly faster than accessing the length property on every iteration of the loop. It is not required to do it this way. It can be done as this also:
for (var i = 0; i < x.length; i++)
The first example (a 'for' loop) will iterate through the elements of an array and is the preferred method of looping through an array.
The latter method (a 'for...in' loop) will iterate through all the properties of an object and is typically more useful for more complex objects than arrays. If you've added any custom properties to the array object, the for...in loop will iterate through them as well, which isn't always desired.
One more thing to keep in mind with for...in loops - they may (depending on browser) not iterate through the object in the order you expect. For more on that, see this answer to another question: https://stackoverflow.com/a/280861/726326