如果我有一个像这样的简单对象:
const currentAccount = [{
name: 'J.Edge',
balance: 100,
}]
首先,我是正确的思考(原谅我的新手,只学习JS几周)我不能直接添加到数字平衡属性,就像在下面的函数中一样,因为JS类型强制转换平衡属性100到一个字符串?
const withdraw = (amount) => {
currentAccount.balance - amount
return Object.keys(currentAccount)
}
其次,最简单的解决方法是什么?
您可以使用赋值运算符+=
和-=
执行此操作。
这与写variable = variable + change
或variable = 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
是一个数组,因此您需要在更改值之前访问其中的元素。