简体   繁体   中英

JavaScript: Why does my object property equal undefined?

Hi I'm a 14 year old programmer. I just spent some time to create a mod for Minecraft Pocket Edition using something called ModPe. ModPe supplies me with a bunch of functions which I can use together, with 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.

entityData is not an object. 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).

Thus, you are not accessing the same object, rather different temporary objects, when operating on your 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) ]
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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