具有 reduce 的对象数组中的字段总和返回 NaN [英] Sum of fields in an array of objects with reduce returns NaN

查看:53
本文介绍了具有 reduce 的对象数组中的字段总和返回 NaN的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现 JavaScript 中的 reduce 函数出现奇怪的行为.

I am seeing a strange behaviour with the reduce function in javascript.

我有一个对象数组,如下所示:

I have an array of objects, made like this:

[ { a:1 }, {a:2}, ... ]

我需要每个对象中 a 属性的总和,所以我写了这个:

I need the sum of the a property inside every object, so I wrote this:

const array = [{a:1}, {a:2}];
const reducer = (accumulator, currentValue) => accumulator.a + currentValue.a;
console.log(array.reduce(reducer));

这按预期工作.

如果我尝试使用包含单个对象的数组运行相同的代码,我会得到该对象作为 reduce 调用的结果(这是预期的行为),所以我添加了一个默认值像这样的reduce函数调用的值:

If I try to run the same code with an array containing a single object, I get that object as the result of the reduce call (and this is expected behaviour), so I added a default value to the reduce function call like this:

const array = [{a:1}];
const reducer = (accumulator, currentValue) => accumulator.a + currentValue.a;
console.log(array.reduce(reducer, {a: 0}));

这也很有魅力.

我希望能够使用包含多个元素的数组运行第二个版本的 reduce 调用,例如:

I would expect to be able to run the second version of the reduce call with an array with more than one element, such as:

const array = [{a:1}, {a:2}];
const reducer = (accumulator, currentValue) => accumulator.a + currentValue.a;
console.log(array.reduce(reducer, {a: 0}));

但这会返回 NaN,我不明白为什么.谁能帮我解释一下?

But this returns NaN and I don't understand why. Could anyone please explain me?

推荐答案

当使用 Array.reduce(),如果不指定初始值,则数组的第一项成为初始值.因为你想要一个数字,而不是一个对象作为结果,初始化为 0.由于累加器现在是一个数字,而不是一个对象,使用 accumulator 而不是 accumulator.a:

const array = [{a:1}, {a:2}, {a:3}];
const reducer = (accumulator, currentValue) => accumulator + currentValue.a;
console.log(array.reduce(reducer, 0));

你也可以检查累加器是否是一个对象,然后尝试访问它的属性,但我发现它比简单地声明一个初始值更令人困惑:

You can also check if the accumulator is an object, and then try to access it's property, but I find it more confusing than simply stating an initial value:

const array = [{a:1}, {a:2}, {a:3}];
const reducer = (accumulator, currentValue) => (typeof accumulator === 'object' ? accumulator.a : accumulator) + currentValue.a;
console.log(array.reduce(reducer));

这篇关于具有 reduce 的对象数组中的字段总和返回 NaN的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆