数组缩减功能返回NAN

时间:2016-09-26 08:53:55

标签: javascript reduce

我的代码如下:

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 (a,b) {
        return a.y + b.y;
    });
console.log(reduced) // returns NAN

3 个答案:

答案 0 :(得分:20)

您可以使用起始值并仅从数组中添加一个值。

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

答案 1 :(得分:3)

简短解决方案:将集合映射到整数集合,并将其缩小

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);

答案 2 :(得分:0)

简短答案:该代码返回了NaN,因为reduce将'a'评估为数字0。

长答案:我曾经认为.reduce()就像.map().filter()一样,只是{{{ 1}}一次处理两个项目,将整个数组缩减为一个项目。这是不正确的。 .reduce()一次处理一个数组项,而 一次“运行总计”。

.reduce()中的第一个参数(运行总计)必须为数字。 .reduce()假定第一个参数为零,除非编码人员另行指定。

因此,在这一行中,.reduce() var reduced=temp.reduce(function (a,b)认为'a'为0,b为.reduce()...。该代码的作者正在编写–就像我做了很多times :) –好像'a'是{"name":"Agency","y":32,"drilldown ...是,而'b'是{"name":"Agency","y":32,...。如果是这种情况,{"name":"ER","y":60,应该是简单的加法。但是a.y + b.y这样做:.reduce(),这当然不起作用,因为整数0没有0.y + b.y键。

因此,@ Nina Sholz的解决方案有效。这是我的解释。