简体   繁体   English

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

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

Hi I'm a 14 year old programmer. 嗨,我是14岁的程序员。 I just spent some time to create a mod for Minecraft Pocket Edition using something called ModPe. 我只是花了一些时间使用称为ModPe的东西为Minecraft Pocket Edition创建一个mod。 ModPe supplies me with a bunch of functions which I can use together, with JavaScript. ModPe为我提供了一堆可以与JavaScript一起使用的功能。 Anyway I see nothing wrong in my code, this is why I come here. 无论如何,我在代码中没有发现任何错误,这就是为什么我来这里。 Here it is: 这里是:

 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 :/ } 

I appreciate your help! 我感谢您的帮助! The object property flyType is basically undefined, don't know what the others are equal to, but most likely undefined as well. 对象属性flyType基本上是未定义的,不知道其他属性等于什么,但很可能也是未定义的。

entityData is not an object. entityData不是对象。 It's a number. 这是一个数字。 Since a number is a primitive, it can't have properties. 由于数字是原始的,因此它不能具有属性。 Consequently, when you access (read/write) one of its properties, a temporary, auto-boxed Number object is created, and it's thrown away immediately (after the expression is evaluated). 因此,当您访问(读/写)其属性之一时,将创建一个临时的自动装箱的Number对象,并且该对象将立即被丢弃(在计算表达式之后)。

Thus, you are not accessing the same object, rather different temporary objects, when operating on your entityData . 因此,在对entityData操作时,您不会访问同一对象,而是不同的临时对象。

The solution: make it into a proper non-primitive object instead: 解决方案:改为将其变成适当的非原始对象:

var entityData = {};

If you want to be elegant as well, you can initialize it with default properties, since object literals permit that too: 如果您还想变得优雅,则可以使用默认属性对其进行初始化,因为对象文字也允许这样做:

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