如何在对象数组上调用reduce来总结它们的属性? [英] How to call reduce on an array of objects to sum their properties?

查看:32
本文介绍了如何在对象数组上调用reduce来总结它们的属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我想对 arr 中的每个元素求和 a.x.

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

我有理由相信 a.x 在某些时候是 undefined.

I have cause to believe that a.x is undefined at some point.

以下工作正常

arr = [ 1, 2, 4 ];
arr.reduce(function(a, b){ return a + b; }); // => 7

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

What am I doing wrong in the first example?

推荐答案

在第一次迭代之后,您将返回一个数字,然后尝试获取它的属性 x 以添加到下一个对象中是 undefined 并且涉及 undefined 的数学结果为 NaN.

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 属性和参数 x 属性总和的对象:

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}

从评论中添加的解释:

[].reduce 每次迭代的返回值,用作下一次迭代中的a 变量.

The return value of each iteration of [].reduce used as the a variable in the next iteration.

迭代1:a = {x:1}, b = {x:2}, {x: 3} 分配给a 在迭代 2 中

Iteration 1: a = {x:1}, b = {x:2}, {x: 3} assigned to a in Iteration 2

迭代 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
}

迭代 1: a = {x:1}, b = {x:2}, //返回 3 作为 >a 在下一次迭代中

Iteration 1: a = {x:1}, b = {x:2}, // returns 3 as a in next iteration

迭代2:a = 3, b = {x:2} 返回NaN

数字文字 3(通常)没有名为 x 的属性,所以它是 undefinedundefined + bx 返回 NaN 并且 NaN + 总是 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

澄清:我更喜欢我的方法而不是该线程中的另一个最佳答案,因为我不同意传递可选参数以使用幻数减少以获取数字原语更清晰的想法.这可能会导致写入的行数减少,但 imo 可读性较差.

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.

这篇关于如何在对象数组上调用reduce来总结它们的属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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