我对Javascript非常陌生,并且使用D&D概念在基础上进行了一些练习,因为我可以很容易地将它们概念化。在这个过程中,我在玩对象,数组和方法。 卡住的地方是如何保存添加到playerOne的“ coin”中的“ Gold”,然后在运行下面的“ getTotalGold”功能时反映出来。我想我可能会缺少一些基本的知识,或者可能只是因为我还很新,所以还没有学到一些东西。任何帮助表示赞赏!
const playerOne = {
name: 'Zolda',
class: 'Wizard',
maxHp: 90,
currentHp: 85,
armorClass: 16,
atkBonus: 7,
coin: [
{
type: 'Gold',
amount: 895,
},
{
type: 'Platinum',
amount: 132,
},
{
type: 'Silver',
amount: 6457,
},
{
type: 'Copper',
amount: 35456,
},
],
items: [],
addItem(description, amount) {
this.items.push({
description,
amount,
});
},
};
//Adding gold to the object array above
function addGold(newGold) {
let currentGold = playerOne.coin[0].amount;
currentGold += newGold;
return currentGold;
}
//converting the other coin values and adding them together in "Gold" for a //estimate of the total value
function getTotalGold() {
const baseGold = playerOne.coin[0].amount;
const platToGold = playerOne.coin[1].amount * 10;
const silverToGold = Math.floor(playerOne.coin[2].amount / 10);
const copperToGold = Math.floor(playerOne.coin[3].amount / 100);
const totalGold = (
baseGold +
platToGold +
silverToGold +
copperToGold
).toFixed(0);
return `${playerOne.name} has about ${totalGold} gold pieces in total.`;
}
console.log(addGold(500));
console.log(getTotalGold());
答案 0 :(得分:0)
您需要将添加的金分配回给对象-仅将变量名称重新分配给新数字不会更改对象的属性:
function addGold(newGold) {
let currentGold = playerOne.coin[0].amount;
currentGold += newGold;
return currentGold;
}
应该是
function addGold(newGold) {
playerOne.coin[0].amount += newGold;
return playerOne.coin[0].amount;
}
const playerOne = {
name: 'Zolda',
class: 'Wizard',
maxHp: 90,
currentHp: 85,
armorClass: 16,
atkBonus: 7,
coin: [
{
type: 'Gold',
amount: 895,
},
{
type: 'Platinum',
amount: 132,
},
{
type: 'Silver',
amount: 6457,
},
{
type: 'Copper',
amount: 35456,
},
],
items: [],
addItem(description, amount) {
this.items.push({
description,
amount,
});
},
};
//Adding gold to the object array above
function addGold(newGold) {
playerOne.coin[0].amount += newGold;
return playerOne.coin[0].amount;
}
//converting the other coin values and adding them together in "Gold" for a //estimate of the total value
function getTotalGold() {
const baseGold = playerOne.coin[0].amount;
const platToGold = playerOne.coin[1].amount * 10;
const silverToGold = Math.floor(playerOne.coin[2].amount / 10);
const copperToGold = Math.floor(playerOne.coin[3].amount / 100);
const totalGold = (
baseGold +
platToGold +
silverToGold +
copperToGold
).toFixed(0);
return `${playerOne.name} has about ${totalGold} gold pieces in total.`;
}
console.log(addGold(500));
console.log(getTotalGold());