【问题标题】:How to write function assigning nested object to parent object property?如何编写将嵌套对象分配给父对象属性的函数?
【发布时间】:2018-10-21 12:35:29
【问题描述】:

我想编写一个 equipWeapon 函数运行,当单击 HTML 图像时,它将对象的 weapon 属性重新分配给 inventory 数组的第一个元素。

HTML:

<img src="bag.png" id="bag" onclick="equipWeapon()">

JS:

const player1= { 
  name: "Bob",
  inventory: [ { type: 'mace', damage: 5 } ],
  health: 10,
  weapon: { 
      type: 'baseball bat',
      damage: 2
       }
};

function equipWeapon2(h) {
    if (h.inventory.length > 0) {
        h.weapon= h.inventory[0]
    } else {

    }
}

function equipWeapon() {
    equipWeapon2(player1);
}

【问题讨论】:

标签: javascript arrays function object


【解决方案1】:

此函数将切换当前玩家的武器属性与武器在库存数组中的位置 0。

function equipWeapon2(h) {
    if (h.inventory.length > 0) {
        let oldWeapon = h.weapon;
        h.weapon= h.inventory[0]
        h.inventory[0] = oldWeapon;
    } else {

    }
}

【讨论】:

  • 感谢您提供此代码 sn-p,它可能会提供一些有限的即时帮助。 proper explanation would greatly improve its long-term value 通过展示为什么这是一个很好的解决问题的方法,并将使其对未来有其他类似问题的读者更有用。请edit您的回答添加一些解释,包括您所做的假设。
猜你喜欢
  • 2011-09-22
  • 1970-01-01
  • 1970-01-01
  • 2014-01-16
  • 2016-01-15
  • 2019-07-22
  • 2014-04-05
  • 2020-05-22
相关资源
最近更新 更多