如何编写将嵌套对象分配给父对象属性的函数?

时间:2018-10-21 12:35:29

标签: javascript arrays function object

当单击HTML图像时,我想编写一个equipWeapon函数运行,该函数将对象的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);
}

1 个答案:

答案 0 :(得分:0)

此功能将在清单阵列中位置为0的武器上切换当前玩家的武器属性。

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

    }
}