我要输出对象属性的名称(“ sword”)。我认为我应该可以通过使用
来做到这一点player.weapon.name
当所有内容都嵌套在一个对象中时,我这样做没有问题,但是当尝试从另一个变量(剑)中获取属性(名称)时,单击“ Equip”按钮时应用程序将中断。经过测试,我确定这是由于
player.weapon.name
行为不正常。
vscode(https://i.imgur.com/Gw4cEnv.png)提供的此弹出窗口表明player.weapon.name应该起作用。我也尝试了括号表示法,但无济于事。引用此属性的正确语法是什么?
// DOM Variables
var equipButton = document.getElementById('equip-button');
// UI Variables
var equipQuery = false;
// Player Variables
var player = {
name: "Player",
health: 100,
armor: 0,
strength: 1,
accuracy: 80,
knowledge: 0,
weapon: sword,
};
equipButton.style.display = 'none';
showStatus();
// Button Handlers
equipButton.addEventListener('click', function() {
equipQuery = true;
showStatus();
});
// Write Screen
function showStatus() {
if (equipQuery == true) { // Clicked Equip Button
textArea.innerText = "You are wielding " + player.weapon.name;
equipQuery = false; // Let's turn off the equip query
equipButton.style.display = 'none'; // Sets the buttons such that the player can go back
return;
}
textArea.innerText = "Your name is " + player.name; // Default Text
}
// Item Objects
var sword = {
name: "sword",
bigname: "Sword",
strength: 0,
accuracy: 0,
type: null,
};
答案 0 :(得分:0)
您在实际为其分配值之前使用sword
,因此它是undefined
(用于验证的console.log(player)
),因此您无法访问它的name
。
这是可能的,因为您使用了var
来允许出现此类错误,请改用let
或const
(对于不变的值),然后指出错误。
let player = { weapon: sword }; // error: variable used before declaration
const sword = {};