To the best of my understanding, the code
var a = new Array("a","b","c");
var out = "";
for(i in a)
out += i+":"+a[i]+"\n";
should set out to
0:a
1:b
2:c
right?
Well, I have the following code snippet in a project of mine:
for(i in player.neededItems)
{
debug(i+":");
if(!player.hasItem(player.neededItems[i].type))
itemsRemaining.push(player.neededItems[i]);
debug(i+"<br />");
}
- debug(x) is simply a function that appends x to the contents of a div with id "debug".
- player.neededItems is an array of objects.
- itemsRemaining is a previously empty array.
- player.hasItem returns wether or not the player has an item.
Ok. So here's where it get's weird. In the for loop, 'i' is only used as an index to an array. It is not modified in any way. However, the output in "debug" is as follows:
0:3
1:3
2:3
3:3
Why is 'i' changing?! player.neededItems does not get modified in any of the functions or anything. I have no idea what is going on. But, when I switch
for(i in player.neededItems)
for
for(i = 0; i < player.neededItems.length; i++)
everything works.
So am I missing something regarding the functionality of 'for(i in a)' syntax? Or have I stumbled upon a bug in the javascript parser in webKit? Or (more likely,) am I going mad?
var i, without thevarkeyword ahead of a variable I believe it is implicitly declared global. There might be some otheriin your program that is interfering.for(var i=0; i<arr.length; i++)or an array iteration method (arr.forEach) instead.