且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Javascript中奇怪的行为增强了...在循环中

更新时间:2022-10-20 13:59:54

The for...in statement is meant to be used to iterate over object properties, by looking your code seems that actors is an Array (you are setting the initial element with index 0).

This statement will also crawl up the prototype chain, if you have extended the Array.prototype those 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:

for (var i = 0; i < actors.length; i++) {
    actors[i].xpos += actor.xvel;
    actors[i].ypos += actor.yvel;
}

If I'm wrong, and actors is not an Array, I would recommend you to use the hasOwnProperty method, to ensure that the property exists in the object itself, not up somewhere in the prototype chain:

for (var name in object) {
  if (object.hasOwnProperty(name)) {
    //
  }
}