javascript - 如何将对象添加到数组中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}]
解决方案
使用计算属性名称- 括号中的表达式,计算结果为键名(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)
推荐阅读
- php - 如何以 php/html 形式输入和显示多行?
- php - 在 PHP 类中获取帖子术语
- html - WordPress/Avada - 如何在中型屏幕上修复环绕图像的文本
- python-3.x - While 循环在需要时不起作用
- python - 初始化二维列表
- json - jq 将 2 个 json 文件中的对象数组中的字段组合到第 3 个 json 文件中
- python - 如何在 Python 中删除以空格作为值的字典项?
- nativescript - 如何在构建时添加应用内购买功能(ios)
- java - 带有 carview 的 RecyclerViewAdapter 仅显示哈希图中的最后一项
- python - `/bin/sh: 1: python: not found` 在 docker 中通过 cron 运行时