首页 > 解决方案 > 当对象是另一个变量的一部分时使用对象内部的对象

问题描述

我想输出一个对象属性的名称(“剑”)。我想我应该能够通过使用来做到这一点

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,
};

标签: javascript

解决方案


sword在实际为其分配值之前使用它,因此它是undefinedconsole.log(player)验证),因此您无法访问它的name.

那是可能的,因为您使用var了允许此类错误,使用letor const(对于不改变的值),然后它会指出这些错误。

  let player = { weapon: sword }; // error: variable used before declaration

  const sword = {};

推荐阅读