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

查看:72
本文介绍了如何在对象数组上调用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} 分配给迭代2中的 a

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 "的属性,因此其为 undefined undefined + bx 返回 NaN ,而 NaN +< anything> 始终为 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天全站免登陆