如何处理对象内部的函数



我正在尝试用javascript处理一个简单的personalAccount对象。我在objects键中创建了一些函数,但是当我试图控制台我的accountBalance函数时,它没有显示欲望输出。

我正在尝试accountSummary键中的收入和支出数据,它应该是我的(totalIncome-totalExpense(=期望输出,但它在我的终端中给出了NaN。

`

const personAccount = {
firstName: 'Prashant',
lastName: 'Singh',
incomes: [20000, 30000, 40000],
expenses: [],
totalIncome: function() {
return this.incomes.reduce((acc, curr) => acc + curr,0);
},
totalExpense: function() {
return this.expenses.reduce((acc, curr) => acc + curr,0);
},
accountInfo: function () {
return `First Name: ${this.firstName}, Last Name: ${this.lastName}, Total Income: ${this.totalIncome()}, Total Expense: ${this.totalExpense()}, Account Balance: ${this.totalIncome() - this.totalExpense()}`
},
addIncome: function (income) {
this.incomes.push(income);
return this.incomes;
},
addExpense: function (expenses){
this.expenses.push(expenses);
return this.expenses;
},
accountBalance: function () {
return this.totalIncome() - this.totalExpense();
},
accountSummary: function () {
return `First Name: ${this.firstName}, Last Name: ${this.lastName}, Balance: ${this.accountBalance()}`
}
}

`

你的代码应该工作得很好,这一切都取决于你是如何访问它的。这是工作演示,请查看并尝试找到根本原因。

const personAccount = {
incomes: [20000, 30000, 40000],
expenses: [],
totalIncome: function() {
return this.incomes.reduce((acc, curr) => acc + curr,0);
},
totalExpense: function() {
return this.expenses.reduce((acc, curr) => acc + curr,0);
},
accountBalance: function () {
return this.totalIncome() - this.totalExpense();
}
};
console.log(personAccount.accountBalance());

最新更新