繁体   English   中英

JavaScript:为什么我的对象属性等于未定义?

[英]JavaScript: Why does my object property equal undefined?

嗨,我是14岁的程序员。 我只是花了一些时间使用称为ModPe的东西为Minecraft Pocket Edition创建一个mod。 ModPe为我提供了一堆可以与JavaScript一起使用的功能。 无论如何,我在代码中没有发现任何错误,这就是为什么我来这里。 这里是:

 if (entityIsPassiveMob(entityId)) { // only add entity to list of entitys if entity is a passive mob var entityData = 1; // variable to be used with properties, it is set to 1 to become an object. An exception can't have a property because its not an object. entityData.flyType = random(1, 4); // 1 = rocketers, 2 = magical, 3 = dizzy, 4 = tired entityData.rocketers = []; entityData.magical = [random(1, 10)]; // amountBlocksAboveGround entityData.dizzy = []; entityData.tired = random(1, 4); // amountBlocksAboveGround listEntitys.push([entityId, entityData]); // push needed data into array clientMessage("added entity as " + entityData.flyType); // this prints undefined in Minecraft PE's chat box :/ } 

我感谢您的帮助! 对象属性flyType基本上是未定义的,不知道其他属性等于什么,但很可能也是未定义的。

entityData不是对象。 这是一个数字。 由于数字是原始的,因此它不能具有属性。 因此,当您访问(读/写)其属性之一时,将创建一个临时的自动装箱的Number对象,并且该对象将立即被丢弃(在计算表达式之后)。

因此,在对entityData操作时,您不会访问同一对象,而是不同的临时对象。

解决方案:改为将其变成适当的非原始对象:

var entityData = {};

如果您还想变得优雅,则可以使用默认属性对其进行初始化,因为对象文字也允许这样做:

var entityData = {
    flyType: random(1, 4),
    rocketers: [],
    magical: [ random(1, 10) ]
};

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM