首页 > 解决方案 > 如何将对象添加到数组中javascript

问题描述

我正在尝试使用 addExpense 方法将对象添加到费用数组中。

const account = {
    expenses: [],
    addExpense: function(description, amount){
        let addObject = {
            description : amount
        }
        this.expenses.push(addObject)
    }
}

account.addExpense('Shopping', 50)
console.log(account.expenses)

我没有收到任何错误,但结果给了我一个使用参数名称而不是实际字符串值“购物”的对象。金额参数工作正常。

[{"description": 50}]

标签: javascript

解决方案


使用计算属性名称- 括号中的表达式,计算结果为键名(description本例中的值):

let addObject = {
    [description] : amount
}

演示:

const account = {
    expenses: [],
    addExpense: function(description, amount){
        let addObject = {
            [description] : amount
        }
        this.expenses.push(addObject)
    }
}

account.addExpense('Shopping', 50)
console.log(account.expenses)


推荐阅读