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

问题描述 投票:0回答:1

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

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

}]

首先,我是正确的思考(原谅我的新手,只学习JS几周)我不能直接添加到数字平衡属性,就像在下面的函数中一样,因为JS类型强制转换平衡属性100到一个字符串?

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

}

其次,最简单的解决方法是什么?

javascript object properties add numeric
1个回答
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是一个数组,因此您需要在更改值之前访问其中的元素。

© www.soinside.com 2019 - 2024. All rights reserved.