为什么不能添加数字对象属性?

时间:2018-08-31 19:55:25

标签: javascript object properties add numeric

如果我有一个像这样的简单对象:

const currentAccount = [{
    name: 'J.Edge',
    balance: 100,

}]

首先,我的想法是对的(原谅我的新手,仅学习JS几周),由于JS类型的强制性,我不能像下面的函数那样直接添加到数值平衡属性中将balance属性的100转换为字符串?

const withdraw = (amount) => {
    currentAccount.balance - amount
    return Object.keys(currentAccount)

}

第二,解决这个问题的最简单方法是什么?

1 个答案:

答案 0 :(得分:1)

您可以使用赋值运算符+=-=来做到这一点。

这与编写variable = variable + changevariable = variable - change

相同

const currentAccount = [{
    name: 'J.Edge',
    balance: 100,

}];

const withdraw = (amount) => {
    currentAccount[0].balance -= amount
}

const deposit = (amount) => {
    currentAccount[0].balance += amount
}

withdraw(20); // => 100 - 20
deposit(45); // => 80 + 45

console.log(currentAccount[0].balance); // => 125

请注意,currentAccount是一个数组,因此您需要在其中更改值之前访问其中的元素。

相关问题