定义为对象的对象返回undefined

时间:2017-12-16 02:22:40

标签: javascript

我将player指定为一个对象,其中包含weapon等属性,这些属性是我定义为stick项的对象,它会附加一个值这可能是伤害。但是,当函数player.weapon.stick调用它时,它将返回错误“Uncaught TypeError:无法读取未定义的属性'棒'”。我相信它说武器是未定义的,但是我定义所有这些的块是

//Player Data
var player = {
weapon: stick,
speed: 3,
armor: cloth,
location: pLocation
}
var pLocation = [tickX, tickY];

//Items
var stick = { stick: 1 };
var cloth = { ClothArmor: 1 };

问题在于我的定义或我如何称呼它player.weapon.stick

4 个答案:

答案 0 :(得分:1)

当您声明cloth时,应该定义

stickplayer,因为它们尚未定义,但其值已解析为undefined且不会更改稍后当你定义它们时。

答案 1 :(得分:1)

最好在使用之前定义变量

var pLocation = [tickX, tickY];

//Items
var stick = { stick: 1 };
var cloth = { ClothArmor: 1 };

//Player Data
var player = {
    weapon: stick,
    speed: 3,
    armor: cloth,
    location: pLocation
}

答案 2 :(得分:1)

JS只提升功能 - 而不是变量。因此,您必须在使用它们之前定义变量。

var pLocation = [tickX, tickY];

    //Items
    var stick = { stick: 1 };
    var cloth = { ClothArmor: 1 };

    //Player Data
    var player = {
    weapon: stick,
    speed: 3,
    armor: cloth,
    location: pLocation
    }

var stick

//Player Data
var player = {
weapon: stick,
speed: 3,
armor: cloth,
location: pLocation
}
var pLocation = [tickX, tickY];

//Items
stick = { stick: 1 };
var cloth = { ClothArmor: 1 };

答案 3 :(得分:0)

这里有几个问题,最重要的一个问题就是你似乎不理解对象(不是试图粗鲁,但是你还在使用它们是错误的)。

var pLocation = [tickX, tickY]; // place this first to avoid undefined location
var player = {
weapon: stick, // stick without quotation marks is a variable, not a string, so this would be player.weapon = stick where stick = undefined variable.
speed: 3,
armor: cloth,
location: pLocation // since pLocation is defined after in your script i currently has no value, so location will be undefined.
}
//alternatively for pLocation
player.location = [tickX, tickY];

//Items
var stick = { stick: 1 }; // this creates an object called stick with a variable called stick with the value 1, so stick.stick = 1.
var cloth = { ClothArmor: 1 }; // this creates an object called cloth with a variable called ClothArmor with the value 1, so cloth.ClothArmor = 1.

因此,如果你调用player.weapon.stick它是不正确的,因为武器不是一个对象,它是一个对象内部的变量。如果你想要player.weapon.stick你必须使用:

player = {
    weapon: {
        stick: 'Variable value'
    }
}