使用Javascript中的变量值访问嵌套对象

时间:2016-05-20 18:51:07

标签: javascript object nested javascript-objects

我正在制作游戏。最终用户将在12种可用战斗机中选择一名战斗机。让我们说他们选择了“Ryu”。但他们本可以选择“春丽”。玩家选择将存储在变量" selectedPlayer'中。现在我需要获取/访问与用户选择匹配的对象(或其成员)。我尝试了很多方法,包括下面显示的方法,但是我进入了控制台:" Uncaught TypeError:无法读取属性' Ryu'未定义的。"

var selectedPlayer = "Ryu";
var Slogan = players[selectedPlayer]['Slogan'];
console.log(Slogan);

var players = {
    Ryu:  {
        Name: "Ryu",
        Country: "Japan",
        Text: "The answer lies in the heart of battle.",
        smImg: "../images/small/ryu.png",
        lgImg: "../images/large/ryu.jpg",
        attack: [1,5,10,15,20,25]
    },
    ChunLi: {
        Name: "Chun Li",
        Country: "China",
        Slogan: "Want to see my Kung-Fu? I'll show you.",
        smImg: "../images/small/chunli.png",
        lgImg: "../images/large/chunli.jpg",
        attack: [1,4,11,15,21,25]
    }
}

我需要能够进入'球员'对象并访问所选择的fighers的成员'宾语。我可以写一堆if语句,但那不是很干净。我可以这样做吗?

var playerOne = {
    Name: players.<some variable>.Name,
    Country: players.<some variable>.Country,
    Slogan: players.<some variable>.Slogan,
    smImage: players.<some variable>.smImg,
    lgImage: players.<some variable>.lgImg,
    Attack: players.<some variable>.attack
};

var playerTwo = {
    Name: players.<some variable>.Name,
    Country: players.<some variable>.Country,
    Slogan: players.<some variable>.Slogan,
    smImage: players.<some variable>.smImg,
    lgImage: players.<some variable>.lgImg,
    Attack: players.<some variable>.attack
};

也许有不同之处。我对任何运作良好的事情持开放态度。谢谢。

2 个答案:

答案 0 :(得分:3)

您需要在访问之前定义映射。另外,Ryu似乎没有Slogan

var players = {
    Ryu:  {
        Name: "Ryu",
        Country: "Japan",
        // Shoudldn't this be "Slogan"?
        Text: "The answer lies in the heart of battle.",
        smImg: "../images/small/ryu.png",
        lgImg: "../images/large/ryu.jpg",
        attack: [1,5,10,15,20,25]
    },
    ChunLi: {
        Name: "Chun Li",
        Country: "China",
        Slogan: "Want to see my Kung-Fu? I'll show you.",
        smImg: "../images/small/chunli.png",
        lgImg: "../images/large/chunli.jpg",
        attack: [1,4,11,15,21,25]
    }
}

var selectedPlayer = "Ryu";
var Slogan = players[selectedPlayer]['Slogan']; 
console.log(Slogan);

答案 1 :(得分:0)

您的错误是因为您在定义之前引用了players。试试这个:

var players = {
    Ryu:  {
        Name: "Ryu",
        Country: "Japan",
        Text: "The answer lies in the heart of battle.",
        smImg: "../images/small/ryu.png",
        lgImg: "../images/large/ryu.jpg",
        attack: [1,5,10,15,20,25]
    },
    ChunLi: {
        Name: "Chun Li",
        Country: "China",
        Slogan: "Want to see my Kung-Fu? I'll show you.",
        smImg: "../images/small/chunli.png",
        lgImg: "../images/large/chunli.jpg",
        attack: [1,4,11,15,21,25]
    }
}

var selectedPlayer = "Ryu";
var Slogan = players[selectedPlayer]['Slogan'];
console.log(Slogan);