Javascript Array Oddness
February 26th, 2006Weird thing about Javascript arrays:
d = [['a','1'],['b','2'],['c','3']]
for (i in d) { alert(i) }
Will pop up 0,1, and 2. That is, iterating through something returns the index of each of the elements of the array. If you want the elements themselves, you have to dereference them:
for (i in d) { alert(d[i]) }
This is nutty, as far as I can tell. I don’t know of any other programming language that does that. Why would you want to loop through the indexes of an array as the default? Python’s approach for example is what seems normal to me:
>>> d = [['a','1'],['b','2'],['c','3']]
>>> for q in d:
... print q
...
['a', '1']
['b', '2']
['c', '3']
If you want the indexes, of course, you can get them like this:
>>> for i in range(len(d)):
... print i
...
0
1
2
That is all.