我正在尝试使用 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”的对象。 amount 参数效果很好。
[{"description": 50}]
最佳答案
使用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)
关于javascript - 如何将对象添加到数组中javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50105865/