调用 reduce 对对象数组求和返回 NaN

IT技术 javascript reduce
2021-02-20 06:14:52

我有类似的代码:

var temp = [ { "y": 32 }, { "y": 60 }, { "y": 60 } ];
var reduced = temp.reduce(function(a, b) {
  return a.y + b.y;
});

console.log(reduced); // Prints NaN

为什么它打印NaN而不是152

2个回答

您可以使用一个起始值,然后从数组中只添加一个值。

var temp=[{"name":"Agency","y":32,"drilldown":{"name":"Agency","categories":["APPS & SI","ERS"],"data":[24,8]}},{"name":"ER","y":60,"drilldown":{"name":"ER","categories":["APPS & SI","ERS"],"data":[7,53]}},{"name":"Direct","y":60,"drilldown":{"name":"Direct","categories":["APPS & SI","ERS"],"data":[31,29]}}];

var reduced = temp.reduce(function (r, a) {
        return r + a.y;
        //    ^^^ use the last result without property
    }, 0);
//   ^^^ add a start value
console.log(reduced) // r

@webmaster,甚至更短,它采用reduce 的起始值来处理空数组: const reduced = temp.reduce((r, { a }) => r + a, 0);
2021-04-21 06:14:52
一个班轮 const 减少 = temp.length ?temp.reduce((r, a) => { return r + ay; }, 0) : 0;
2021-05-19 06:14:52

简短的解决方案:将集合映射到整数集合,并减少它

var temp=[{"name":"Agency","y":32,"drilldown":{"name":"Agency","categories":["APPS & SI","ERS"],"data":[24,8]}},{"name":"ER","y":60,"drilldown":{"name":"ER","categories":["APPS & SI","ERS"],"data":[7,53]}},{"name":"Direct","y":60,"drilldown":{"name":"Direct","categories":["APPS & SI","ERS"],"data":[31,29]}}];

var reduced = temp
                .map(function(obj) { return obj.y; })
                .reduce(function(a, b) { return a + b; });

console.log(reduced);