![](/img/trans.png)
[英]How do I use Square Bracket Notation to use multiple variables to call nested objects?
[英]How do I access an objects key in bracket notation?
我似乎無法弄清楚如何使用括號表示法訪問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);
您需要從屬性名稱中獲得對槍的引用,如下所示:
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!");
}
}
這是我最終使用的內容:
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.