我正在尝试使用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}]
答案 0 :(得分:1)
使用computed property names - 括号中的表达式,用于计算键名(在本例中为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)
&#13;
答案 1 :(得分:0)
现在,您正在设置&#34;描述&#34;财产静态。你想要一个computed property name,如下所示:
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)
&#13;
答案 2 :(得分:0)
let account = {
expenses: [],
addExpense: function(description, amount){
let addObject = {};
addObject[description] = amount
this.expenses.push(addObject)
}
}
account.addExpense('Shopping', 50)
console.log(account.expenses)