javascript - 为什么我无法添加到数字对象属性?

标签 javascript object properties addition numeric

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

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/

相关文章:

javascript - 为什么 `Object() === new Object()` 等于 `false` ?

objective-c - ivars 的行为不符合预期

ios - 在 Swift 3.1 中使用自定义 Setter 更新数组属性

java - 在 Hazelcast XML 配置中使用属性文件值

javascript - 如何销毁 stateChange 上的 $scope 值?

javascript - 网站上音频播放器的 slider 搜索栏拖动功能

powershell - 是否有在 Powershell 5 类中创建脚本属性的正确方法

javascript - react : input type ="checkbox" onChange not triggered

javascript - jQuery 微调器 : Non-numerical values

javascript - 如何检查对象的属性值?