[英]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.