使用 reduce() 与 forEach() 的非原始数组元素的总和
Sum of non-primitive array elements with reduce() vs forEach()
我玩过下面的代码,我无法解释为什么结果不同:
let foo = [];
let bar = [...foo, {
a: 1
}, {
a: 2
}];
let sum = bar.reduce((a, b) => a.a + b.a, 0);
console.log(sum); // prints NaN
sum = 0;
bar.forEach((element) => {
sum += element.a;
});
console.log(sum); // prints 3
问题是 reduce()
链,您需要 return 一个可以作为“下一个 a
” 的值。由于您在整数上引用 a.a
,因此它进入 NaN
范围。
let sum = bar.reduce((a, b) => ({ a: a.a + b.a }), { a: 0 });
一种可能更有效的方法是首先对值进行标准化:
let sum = bar.map(a => a.a).reduce((a, b) => a + b, 0);
现在它只是一个简单的数字数组。
reduce函数的第一个参数是一个累加器。根据定义
The accumulator accumulates callback's return values. It is the accumulated value previously returned in the last invocation of the callback—or initialValue, if it was supplied (see below).
如果您从 a.a
更改为 a
那么它应该可以工作。
let sum = bar.reduce((a, b) => a + b.a, 0);
你的问题是 (a, b) =>
中的 a
是 reduce
的累加器,它从 0
(第二个参数)开始。这意味着它没有 a
属性,因此所有后续总和最终为 NaN
,因为您要将数字添加到 undefined
(以及随后的 NaN
) .要解决此问题,只需删除对 .a
:
的引用
let foo = [];
let bar = [...foo, {
a: 1
}, {
a: 2
}];
let sum = bar.reduce((a, b) => a + b.a, 0);
console.log(sum); // prints 3
您传递给 reduce 函数的初始值为 0,即。 a = 0 并尝试对 undefined + 1 进行计算,其中 returns NaN。您可以执行以下任一操作:
不传递初始值:
bar.reduce((a, b) => a.a + b.a);
通过传递初始值,bur在这里你需要使用地图:
bar.map(a => a.a).reduce((a, b) => a + b, 0);
虽然可以有更多的方法。你可以获得更多here
我玩过下面的代码,我无法解释为什么结果不同:
let foo = [];
let bar = [...foo, {
a: 1
}, {
a: 2
}];
let sum = bar.reduce((a, b) => a.a + b.a, 0);
console.log(sum); // prints NaN
sum = 0;
bar.forEach((element) => {
sum += element.a;
});
console.log(sum); // prints 3
问题是 reduce()
链,您需要 return 一个可以作为“下一个 a
” 的值。由于您在整数上引用 a.a
,因此它进入 NaN
范围。
let sum = bar.reduce((a, b) => ({ a: a.a + b.a }), { a: 0 });
一种可能更有效的方法是首先对值进行标准化:
let sum = bar.map(a => a.a).reduce((a, b) => a + b, 0);
现在它只是一个简单的数字数组。
reduce函数的第一个参数是一个累加器。根据定义
The accumulator accumulates callback's return values. It is the accumulated value previously returned in the last invocation of the callback—or initialValue, if it was supplied (see below).
如果您从 a.a
更改为 a
那么它应该可以工作。
let sum = bar.reduce((a, b) => a + b.a, 0);
你的问题是 (a, b) =>
中的 a
是 reduce
的累加器,它从 0
(第二个参数)开始。这意味着它没有 a
属性,因此所有后续总和最终为 NaN
,因为您要将数字添加到 undefined
(以及随后的 NaN
) .要解决此问题,只需删除对 .a
:
let foo = [];
let bar = [...foo, {
a: 1
}, {
a: 2
}];
let sum = bar.reduce((a, b) => a + b.a, 0);
console.log(sum); // prints 3
您传递给 reduce 函数的初始值为 0,即。 a = 0 并尝试对 undefined + 1 进行计算,其中 returns NaN。您可以执行以下任一操作:
不传递初始值:
bar.reduce((a, b) => a.a + b.a);
通过传递初始值,bur在这里你需要使用地图:
bar.map(a => a.a).reduce((a, b) => a + b, 0);
虽然可以有更多的方法。你可以获得更多here