我似乎无法弄清楚如何使用括号表示法访问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);
答案 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!");
}