如何将对象添加到数组javascript中

时间:2018-04-30 18:01:46

标签: 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}]

3 个答案:

答案 0 :(得分:1)

使用computed property names - 括号中的表达式,用于计算键名(在本例中为description值):

let addObject = {
    [description] : amount
}

<强>演示:

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

account.addExpense('Shopping', 50)
console.log(account.expenses)
&#13;
&#13;
&#13;

答案 1 :(得分:0)

现在,您正在设置&#34;描述&#34;财产静态。你想要一个computed property name,如下所示:

let addObject = {
   [description] : amount
}

完整示例:

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

account.addExpense('Shopping', 50)
console.log(account.expenses)
&#13;
&#13;
&#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)