I am making a Javascript game with the canvas tag, and I am using an enhanced for loop to update the player positions.
In brief:
var actors = new Array();
var player = new Actor(0, 0, img);
actors[0] = player;
function update_positions() {
//position 1
for(var a in actors) {
//position2
a.xpos += a.xvel;
a.ypos += a.yvel;
}
}
Just outside of the for loop at position 1, I can access the correct value of actors[0].xvel. Inside the for loop at position 2, a.xvel is undefined. Can someone explain to me what is happening?
The
for...instatement is meant to be used to iterate over object properties, by looking your code seems thatactorsis an Array (you are setting the initial element with index0).This statement will also crawl up the prototype chain, if you have extended the
Array.prototypethose properties will be iterated, and also the order of iteration is not warranted.I would recommend you to avoid problems and iterate using a normal for loop:
If I’m wrong, and
actorsis not an Array, I would recommend you to use thehasOwnPropertymethod, to ensure that the property exists in the object itself, not up somewhere in the prototype chain: