Javascript在对象数组上减少 [英] Javascript reduce on array of objects
问题描述
假设我想为 arr
中的每个元素添加 ax
。
$ (b,b)$ b $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ {return ax + bx})
>> NaN
我有理由相信ax在某些时候是未定义的。
以下工作正常
arr = [1,2,4]
arr .reduce(function(a,b){return a + b})
>> 7
第一个例子中我做错了什么?
未定义
的对象和涉及 undefined
的数学结果为 NaN
。 尝试使用参数的x属性之和返回包含 x
属性的对象:
var arr = [{x:1},{x:2},{x:4}] ;
arr.reduce(函数(a,b){
return {x:ax + bx}; //返回具有属性x
的对象))
$ b(b,b)=>({x:ax + bx}));
// - > {x:7}
来自评论的说明:
在下一次迭代中用作 a
变量的 []。reduce
的每次迭代的返回值。
$ b
迭代1: a = {x:1}
, b = {x: 2}
, {x:3}
在迭代2中分配给 a
迭代2: a = {x:3}
, b = {x:4}
。
您示例的问题在于您要返回数字字面值。
function(a,b){
return ax + bx; //返回数字字面值
}
迭代1: a = {x:1}
, b = {x:2}
, //返回3
在下一次迭代中作为 a
迭代2: a = 3
, b = {x:2}
返回 NaN
数字文字 3
通常不具有名为 x
的属性,因此它的未定义
和未定义+ bx
返回 NaN
和 NaN +< anything>
总是 NaN
澄清:我更喜欢我的方法而不是这个线程中的其他顶级答案,因为我不同意使用一个可选参数来减少一个幻数以获得一个数字原语的想法更清晰。它可能会导致更少的行被写入,但它可读性差。
Say I want to sum a.x
for each element in arr
.
arr = [{x:1},{x:2},{x:4}]
arr.reduce(function(a,b){return a.x + b.x})
>> NaN
I have cause to believe that a.x is undefined at some point.
The following works fine
arr = [1,2,4]
arr.reduce(function(a,b){return a + b})
>> 7
What am I doing wrong in the first example?
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
.
try returning an object contain an x
property with the sum of the x properties of the parameters:
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.
Iteration 1: a = {x:1}
, b = {x:2}
, {x: 3}
assigned to a
in Iteration 2
Iteration 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
Iteration 2: a = 3
, b = {x:2}
returns NaN
A number literal 3
does not (typically) have a property called x
so it's undefined
and undefined + b.x
returns NaN
and NaN + <anything>
is always 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.
这篇关于Javascript在对象数组上减少的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!