嗨,我是一名 14 岁的程序员。我刚刚花了一些时间使用 ModPe 为 Minecraft 袖珍版创建了一个模组。 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) ]
};
关于JavaScript:为什么我的对象属性等于未定义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26951774/