JavaScript对象内函数处理问题:accountBalance返回NaN排查
问题解决:personalAccount对象方法返回NaN/不符合预期的问题
核心问题
你的代码里模板字符串的反斜杠转义是错误的,在accountInfo和accountSummary方法中,你用了\``来包裹模板字符串,这会导致JavaScript无法正确解析模板字符串,进而在计算this.totalIncome() - this.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 (expense){ this.expenses.push(expense); return this.expenses; }, accountBalance: function () { return this.totalIncome() - this.totalExpense(); }, accountSummary: function () { return `First Name: ${this.firstName}, Last Name: ${this.lastName}, Balance: ${this.accountBalance()}`; } };
关键修正点
- 移除
accountInfo和accountSummary方法中模板字符串的反斜杠\,直接使用``包裹字符串内容,让JavaScript能正确解析插值表达式。 - 可选优化:把
addExpense的参数名从expenses改为expense,和对象的expenses数组名区分开,避免语义混淆。
测试验证
调用方法测试效果:
console.log(personAccount.accountBalance()); // 输出90000 console.log(personAccount.accountSummary()); // 输出"First Name: Prashant, Last Name: Singh, Balance: 90000" personAccount.addExpense(15000); console.log(personAccount.accountBalance()); // 输出75000
内容的提问来源于stack exchange,提问作者Prashant Singh
相关产品推荐
相关产品推荐

