Possible Duplicate:
JavaScript “For …in” with Arrays
I looped over various arrays using for-in iteration, with varying results:
var my_array1 = {"foo":2, "bar":3};
var my_array2 = new Array(
'foo',
'bar'
);
var my_array3 = ["foo","bar"];
for (var key in my_array1){
alert(key); // outputs key
}
for (var key in my_array2){
alert(key); // outputs index integer not value
}
for (var key in my_array3){
alert(key); // outputs index integer not value
}
Is there a reason that the for-in iteration over non-associative arrays just gives the index and not the actual value like in python?
Is there an advantage to using for(var index in my_array) over using for(var index=0; index<my_array.length; index++), for non-associative arrays?
Simply:
Your first array is not an array.
It’s an object-literal.
Think of it as the instance of a class, where all properties and methods are public.
You could think of it as a singleton, if you really, really wanted, except without any of the global-scope issues that other languages create, trying to make singletons.
So in javascript
for (key in obj) {}is meant to iterate through properties of a class-instance.Use
for (i = 0, length = x; i < length; i += 1) {}for iterating through arrays.