如何以括号表示法访问对象键?

时间:2015-03-16 20:43:24

标签: javascript javascript-objects

我似乎无法弄清楚如何使用括号表示法访问spearguns对象。我正试图访问“heft”键。控制台日志说“未定义”。任何帮助都会很棒,谢谢。

var rockSpearguns = {
  Sharpshooter: {barbs: 2, weight: 10, heft: "overhand"},
  Pokepistol: {barbs: 4, weight: 8, heft: "shoulder"},
  Javelinjet: {barbs: 4, weight: 12, heft: "waist"},
  Firefork: {barbs: 6, weight: 8, heft: "overhand"},
  "The Impaler": {barbs: 1, weight: 30, heft: "chest"}
};

function listGuns(guns) {
  for (var speargun in guns) {
    // modify the log message here
    console.log("Behold! " + speargun + ", with " + this["heft"] + " heft!");
  }
}

listGuns(rockSpearguns);

2 个答案:

答案 0 :(得分:0)

您需要从属性名称中获取对枪的引用,如下所示:

var rockSpearguns = {
                Sharpshooter: {barbs: 2, weight: 10, heft: "overhand"},
                Pokepistol: {barbs: 4, weight: 8, heft: "shoulder"},
                Javelinjet: {barbs: 4, weight: 12, heft: "waist"},
                Firefork: {barbs: 6, weight: 8, heft: "overhand"},
                "The Impaler": {barbs: 1, weight: 30, heft: "chest"}
};

function listGuns(guns) {
    for (var speargun in guns) {
        // modify the log message here
        var gun = guns[speargun];
        console.log("Behold! " + speargun + ", with " + gun["heft"] + " heft!");
    }
}

答案 1 :(得分:0)

以下是我最终使用的内容:

function listGuns(guns) {
  for (var speargun in guns) {
    // modify the log message here

    console.log("Behold! " + speargun + ", with " + guns[speargun]["heft"] + " heft!");
  }