如何合并两个逻辑相同仅操作变量不同的JavaScript函数
问题原因
你写的通用函数存在两处核心问题:
- reduce回调中直接累加
arg3,没有从当前遍历的数组元素上读取对应属性的值,自然无法得到正确的求和结果 - 额外判断数组长度的逻辑是冗余的,reduce指定初始值为0时,空数组的计算结果天然就是0,完全可以覆盖原逻辑
修正后的通用函数实现
function total(list, summaryElement, countPropName) { const sumResult = list.reduce((totalValue, currentItem) => { // 用方括号属性访问器读取当前元素上指定属性的值累加 return totalValue + currentItem[countPropName]; }, 0); summaryElement.textContent = sumResult; return sumResult; }
调用方式
原来的两个求和函数可以直接简化为对通用函数的调用,和你原有逻辑完全兼容:
function totalSpendings() { return total.call(this, this.spendingList, this.spending_summary, 'inputSpending'); } function totalEarnings() { return total.call(this, this.earningList, this.earning_summary, 'inputEarning'); }
如果total函数本身就是挂载在你当前上下文对象上的方法,直接用this.total(...)调用即可,不需要加call绑定上下文。
内容的提问来源于stack exchange,提问作者Zod
相关产品推荐
相关产品推荐

