You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在JavaScript对象中累加值?累加结果为NaN的问题排查

问题原因与解决方案

为何累加结果是NaN?

你的json数据里,第四个条目fourth的type对象缺少target属性,导致val.type.target返回undefined。当数字与undefined相加时,结果会变成NaN,后续所有累加操作都会基于NaN,最终输出自然也是NaN。

修复方案

1. 兼容缺失值的循环累加

在累加时判断target是否存在,不存在则用0替代:

let totals = 0;
for (const val of Object.values(json.consolidated.byLocation)) {
    totals += val.type.target ?? 0; // 空值合并运算符,undefined时取0
}
console.log(totals);

2. 更简洁的函数式写法(避免预声明变量)

使用Array.reduce()方法,一次性完成遍历与累加,符合你想要的简洁风格:

const totals = Object.values(json.consolidated.byLocation).reduce((sum, item) => {
    return sum + (item.type.target ?? 0);
}, 0); // 初始累加值设为0
console.log(totals);

也可以简化为一行:

const totals = Object.values(json.consolidated.byLocation).reduce((s, i) => s + (i.type.target ?? 0), 0);

测试结果

用你提供的示例数据,正确总和为345 + 425 + 383 + 0 = 1153,上述代码均可得到该结果。

内容的提问来源于stack exchange,提问作者MattVotes

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 13:25:21