javascript中的对象操作数组
我在对象内部有一个空数组,如下所示javascript中的对象操作数组,javascript,arrays,object,Javascript,Arrays,Object,我在对象内部有一个空数组,如下所示 const account = { name: "David Reallycool", expenses: [] } 我需要创建一个函数,将费用添加到一个空数组中,结果是 const account = { name: "David Reallycool", expenses: [ { descrition: "Rent", amount: 1000 }, { description:
const account = {
name: "David Reallycool",
expenses: []
}
我需要创建一个函数,将费用添加到一个空数组中,结果是
const account = {
name: "David Reallycool",
expenses: [
{
descrition: "Rent",
amount: 1000
},
{
description: "Coffee",
amount: 2.50
}
]
如何操作它?为此,您需要知道两件事:
const addExpense = (expense) => {
account.expenses.push(expense)
}
// use like this
addExpense({ description: 'Rent', amount: 1000 })
addExpense({ description: 'Coffee', amount: 2.5 })
Array
prototype的push()
函数将该对象添加到expenses
数组中function addExpense(费用,支出){
费用推送(费用);
}
常量帐户={
名称:“David Reallycool”,
费用:[]
};
风险值费用={
描述:“租金”,
金额:1000
}
附加费用(账户、费用、支出);
风险值费用={
描述:“咖啡”,
金额:2.5
}
附加费用(账户、费用、支出);
控制台日志(帐号)代码>作为对象(帐户)而不是副本传输,您可以在函数内部毫无问题地对其进行操作
function addExpenses(inputAccount){
inputAccount.expenses = [
{
descrition: "Rent",
amount: 1000
},
{
description: "Coffee",
amount: 2.50
}
]
}
// will be called with
addExpenses(account);
// here account will have expenses content
可能重复的
const account = {
name: "David Reallycool",
expenses: []
}
function addExpense(description, amount){
account.expenses.push({"description": description, "amount":amount});
}
addExpense("Test", 500);
console.log(account);