[英]How do I access an objects key in bracket notation?
I can't seem to figure out how to access the spearguns object using bracket notation. 我似乎无法弄清楚如何使用括号表示法访问spearguns对象。 I'm trying to access the "heft" key. 我正在尝试访问“ heft”键。 The console log say's "undefined". 控制台日志说“未定义”。 Any help would be great, thanks. 任何帮助将是巨大的,谢谢。
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);
You need to get a reference to the gun from the property name like this: 您需要从属性名称中获得对枪的引用,如下所示:
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!");
}
}
Here is what I ended up using: 这是我最终使用的内容:
function listGuns(guns) {
for (var speargun in guns) {
// modify the log message here
console.log("Behold! " + speargun + ", with " + guns[speargun]["heft"] + " heft!");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.