After the first iteration your're returning a number and then trying to get property x
of it to add to the next object which is undefined
and maths involving undefined
results in NaN
.
(在第一次迭代之后,你将返回一个数字,然后尝试获取它的属性x
以添加到undefined
的下一个对象以及涉及NaN
中undefined
结果的数学。)
try returning an object contain an x
property with the sum of the x properties of the parameters:
(尝试返回一个包含x
属性的对象,其中包含参数的x
属性之和:)
var arr = [{x:1},{x:2},{x:4}];
arr.reduce(function (a, b) {
return {x: a.x + b.x}; // returns object with property x
})
// ES6
arr.reduce((a, b) => ({x: a.x + b.x}));
// -> {x: 7}
Explanation added from comments:
(从评论中添加的解释:)
The return value of each iteration of [].reduce
used as the a
variable in the next iteration.
(的每次迭代的返回值[].reduce
用作a
在下一迭代变量。)
Iteration 1: a = {x:1}
, b = {x:2}
, {x: 3}
assigned to a
in Iteration 2
(迭代1: a = {x:1}
b = {x:2}
{x: 3}
分配给a
在迭代2)
Iteration 2: a = {x:3}
, b = {x:4}
.
(迭代2: a = {x:3}
, b = {x:4}
。)
The problem with your example is that you're returning a number literal.
(你的例子的问题是你正在返回一个数字文字。)
function (a, b) {
return a.x + b.x; // returns number literal
}
Iteration 1: a = {x:1}
, b = {x:2}
, // returns 3
as a
in next iteration
(迭代1: a = {x:1}
b = {x:2}
// returns 3
作为a
在下一迭代)
Iteration 2: a = 3
, b = {x:2}
returns NaN
(迭代2: a = 3
, b = {x:2}
返回NaN
)
A number literal 3
does not (typically) have a property called x
so it's undefined
and undefined + bx
returns NaN
and NaN + <anything>
is always NaN
(数字3
不会(通常)具有名为x
的属性,因此它undefined
且未undefined + bx
返回NaN
和NaN + <anything>
始终为NaN
)
Clarification : I prefer my method over the other top answer in this thread as I disagree with the idea that passing an optional parameter to reduce with a magic number to get out a number primitive is cleaner.
(澄清 :我更喜欢我的方法而不是这个帖子中的另一个顶级答案,因为我不同意传递一个可选参数来减少一个幻数来获得一个数字原语的想法更清晰。)
It may result in fewer lines written but imo it is less readable.(它可能导致写入更少的行,但是它的可读性更低。)