Javascript 中的奇怪行为增强了 for...in 循环 [英] Strange behavior in Javascript enhanced for...in loop

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

问题描述

我正在制作一个带有 canvas 标签的 Javascript 游戏,我正在使用增强的 for 循环来更新玩家位置.

I am making a Javascript game with the canvas tag, and I am using an enhanced for loop to update the player positions.

简而言之:

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;
    }
}

就在位置 1 的 for 循环之外,我可以访问 actor[0].xvel 的正确值.在位置 2 的 for 循环内, a.xvel 未定义.有人可以向我解释发生了什么吗?

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?

推荐答案

for...in 语句旨在用于迭代对象属性,通过查看您的代码似乎actorscode> 是一个数组(您正在使用索引 0 设置初始元素).

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).

该语句还将爬取原型链,如果您已经扩展了Array.prototype 那些属性会被迭代,并且迭代的顺序也没有保证.

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.

我建议您避免问题并进行迭代使用普通的 for 循环:

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;
}

如果我错了,并且actors 不是数组,我会建议你使用hasOwnProperty 方法,以确保该属性存在于对象本身中,不在原型链的某个地方:

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 中的奇怪行为增强了 for...in 循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆