Reputation: 3407
I think there must be a question like this before but current search engines cannot give you results to queries of code lines.
My question is:
What's the difference between
for ( var i = 0; i < array.length; i ++ )
console.log(array[i]);
and
for ( var e in array )
console.log(e);
In my case, the first returns 'undefined' or sequence of number, while the second works fine.
Upvotes: 3
Views: 3125
Reputation: 1
I beleive the real question here should be what's the differenct between:
for ( var i = 0; i < array.length; i ++ )
console.log(array[i]);
and:
for ( var e in array )
console.log(array[e]);
because you should be comparing 2 functions that are supposed to display the same thing.
Upvotes: 0
Reputation: 25728
for...in
can actually be a problem when iterating javascript arrays. It iterates over all the property names in the array, so it may hit more than the actual array values. If you were to say
array.custom ="x"
then it would print "custom" along with any other properties and all the indices of the array.
The other result goes over the length of the array and will pass the indices of each item in the array. It is the safer way to iterate over arrays in Javascript.
Upvotes: 2
Reputation: 4328
Well the first one goes through the indices of the elements in the array. The second one goes through the properties and methods in any object, given an array is also a regular object which has "special" native features (the numerical indexing of elements) it can also go through the second loop as any other object could, the difference is: In the first way, the elements indexed in the array will show up. In the second way, not only that will be iterated over, but also any other property and method that the array object has inherited.
Upvotes: 2