javascript - 当对象是另一个变量的一部分时使用对象内部的对象
问题描述
我想输出一个对象属性的名称(“剑”)。我想我应该能够通过使用来做到这一点
player.weapon.name
当所有内容都嵌套在一个对象中时,我可以毫无困难地执行此操作,但是当尝试从另一个变量(剑)中获取属性(名称)时,应用程序会在单击“装备”按钮时中断。经过测试,我确信这是由于
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,
};
解决方案
您sword
在实际为其分配值之前使用它,因此它是undefined
(console.log(player)
验证),因此您无法访问它的name
.
那是可能的,因为您使用var
了允许此类错误,使用let
or const
(对于不改变的值),然后它会指出这些错误。
let player = { weapon: sword }; // error: variable used before declaration
const sword = {};
推荐阅读
- r - 根据闪亮应用中的 if 条件在同一动态 tabPanel 中导航
- here-api - 批量地理编码器是否已接近使用寿命?
- pytorch - 当训练损失减少时,验证损失增加和准确度保持为零的原因可能是什么?
- kivy - Kivy:RecycleView 未更新
- node.js - 具有数据库访问权限的单元测试 HTTP Post 请求
- php - 如何从 laravel 中的数组中获取多少条记录
- javascript - 打开第二个选项卡级别时,嵌套的 MaterialUI 选项卡会引发错误
- angular - 在 Angular 中将当前的 css 样式表更改为 scss
- c - 我对 C 中的优先规则有疑问
- ios - SwiftUI navigationView 仅从第二个屏幕返回,而不是从下一个屏幕返回