Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
307 views
in Technique[技术] by (71.8m points)

javascript - Javascript减少了对象数组(Javascript reduce on array of objects)

Say I want to sum ax for each element in arr .

(说我要总结ax在每个元素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 ax is undefined at some point.

(我有理由相信ax在某些时候是不确定的。)

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?

(我在第一个例子中做错了什么?)

  ask by YXD translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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的下一个对象以及涉及NaNundefined结果的数学。)

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 = 3b = {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返回NaNNaN + <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.

(它可能导致写入更少的行,但是它的可读性更低。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...