如果我有一个像这样的简单对象:
const currentAccount = [{
name: 'J.Edge',
balance: 100,
}]
首先,我的想法是否正确(原谅我的新手,只学习了几周的 JS),因为 JS 类型强制,我无法直接添加到数字余额属性,就像下面的函数一样将余额属性的 100 转换为字符串?
const withdraw = (amount) => {
currentAccount.balance - amount
return Object.keys(currentAccount)
}
其次,解决这个问题的最简单方法是什么?
最佳答案
您可以使用赋值运算符+=
和-=
来完成此操作。
这与编写变量 = 变量 + 更改
或 变量 = 变量 - 更改
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
是一个数组,因此您需要在更改值之前访问其中的元素。
关于javascript - 为什么我无法添加到数字对象属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52121918/