如何正确使用reduce()对对象数组属性求和?解决返回NaN问题
解决reduce()求和返回NaN的问题
嘿,我来帮你搞定这个问题~你遇到的NaN问题,核心原因是没有给reduce()设置初始累加值,咱们一步步拆解:
为什么你的代码会返回NaN?
你写的这段代码:
BUILDINGS.reduce(function(a,b) {return a.production.numberProd + b.production.numberProd});
执行过程是这样的:
- 第一次调用回调函数时,
a是数组的第一个元素({ production: {"numberProd": 6}}),b是第二个元素,返回值是6 + 11 = 17(一个数字)。 - 第二次调用回调函数时,
a就变成了17这个数字,而数字根本没有production属性,所以a.production会是undefined,再访问numberProd自然就得到NaN了,最终结果就是NaN。
正确的写法
给reduce()加上初始值0,让累加器从数字开始,每次只需要把当前元素的numberProd加到累加器上就行:
var BUILDINGS = [ { production: {"numberProd": 6}}, { production: {"numberProd": 11}}, { production: {"numberProd": 14}}, ]; // 普通函数写法 const totalProduction = BUILDINGS.reduce(function(accumulator, currentBuilding) { return accumulator + currentBuilding.production.numberProd; }, 0); // 这里的0就是初始累加值 console.log(totalProduction); // 输出31
如果喜欢更简洁的箭头函数,也可以写成:
const totalProduction = BUILDINGS.reduce((acc, curr) => acc + curr.production.numberProd, 0);
补充:不设置初始值的兼容写法(不推荐)
如果非要省略初始值,得手动判断累加器的类型,但这种方式容易出错,可读性也差,不建议使用:
const totalProduction = BUILDINGS.reduce(function(a, b) { const currentAccumulator = typeof a === 'object' ? a.production.numberProd : a; return currentAccumulator + b.production.numberProd; });
总的来说,给reduce()设置明确的初始值是最佳实践,既能避免这类奇怪的NaN问题,也让代码逻辑更清晰~
内容的提问来源于stack exchange,提问作者bejewelled
相关产品推荐
相关产品推荐

