繁体   English   中英

如何将对象添加到数组中

[英]How to add object into an array 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) 

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

[{"description": 50}]

使用计算的属性名称 -方括号中的表达式,其值为键名(在这种情况下为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) 

现在,您正在静态设置“ 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) 

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM