gpt4 book ai didi

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

转载 作者:数据小太阳 更新时间:2023-10-29 05:40:29 25 4
gpt4 key购买 nike

我有类似的代码:

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

最佳答案

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

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

关于javascript - 调用 reduce 对对象数组求和返回 NaN,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39698450/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com