[英]How to write function assigning nested object to parent object property?
I want to write an equipWeapon
function runs, when an HTML image is clicked, which reassigns the weapon
property of the object to the first element of the inventory
array. 我想编写一个单击HTML图像时运行的equipWeapon
函数,该函数将对象的weapon
属性重新分配给inventory
数组的第一个元素。
HTML: HTML:
<img src="bag.png" id="bag" onclick="equipWeapon()">
JS: 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);
}
This function will switch the current player's weapon property with the weapon in position 0 at the inventory array. 此功能将在清单阵列中位置为0的武器上切换当前玩家的武器属性。
function equipWeapon2(h) {
if (h.inventory.length > 0) {
let oldWeapon = h.weapon;
h.weapon= h.inventory[0]
h.inventory[0] = oldWeapon;
} else {
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.