本文介绍了Javascript中奇怪的行为增强了...在循环中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



简单地说:



  var actors = new Array(); 

var player = new Actor(0,0,img);

actors [0] = player;
$ b $函数update_positions(){
//位置1
for(var a in actors){
// position2
a.xpos + = a .xvel;
a.ypos + = a.yvel;




$ b $ p $就在位置1的for循环之外,可以访问actors [0] .xvel的正确值。在位置2的for循环中,a.xvel是未定义的。有人可以向我解释发生了什么事情吗? 语句旨在用于迭代over object properties ,看起来你的代码看起来像 actors 是一个数组(你正在设置索引 0 )。



这个声明也将 抓取原型链,如果扩展了 Array.prototype ,那么这些属性将被迭代,迭代次序也不会保证。



我建议你避免 and iterate using a normal for loop: ; i< actors.length; i ++){
actors [i] .xpos + = ac tor.xvel;
actors [i] .ypos + = actor.yvel;如果我错了, actors





不是数组,我建议你使用 hasOwnProperty 方法,以确保该属性存在于对象本身中,而不是在原型的某处链:

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


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...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)) {
    //
  }
}

这篇关于Javascript中奇怪的行为增强了...在循环中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 18:31