0

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?

Community
  • 1
  • 1
shafty
  • 609
  • 7
  • 17
  • Yes, the for-in was confusingly named and is a common source of mistakes because of that. If you want a python-style foreach loop use the Array.prototype.forEach method (or write a similar method of your own) – hugomg Jul 19 '12 at 19:10
  • In `javascript` there is no such thing as `associative array` instead there is `object` like `{key:value}`. – The Alpha Jul 19 '12 at 19:15

3 Answers3

1

for..in iterates over properties, not values.

As described in the above link, a theoretical disadvantage of using it instead of a regular for with Arrays is that the iteration order of properties is not defined in the ECMAScript spec (see the text under this section), and is this implementation dependent.

Jonny Buchanan
  • 61,926
  • 17
  • 143
  • 150
0

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.

Norguard
  • 26,167
  • 5
  • 41
  • 49
0

I'm guessing the reason basically boils down to being the way the whomever designed the Javascript 'in' operator. This behavior is similar to some other languages, in that in the case of the object/hash the keys are 'foo' and 'bar' while for an array the keys are the indexes. I wouldn't see a big difference between using a 'standard' for loop and a 'for in' loop for an array, although as a point of clarity I'd tend to used the standard notation unless I was using something like a .each() function which would take care of it for me.

Robert
  • 2,441
  • 21
  • 12