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

JavaScript使用reduce计算对象数组分数总和时出现NaN的解决方法

为什么reduce计算分数总和返回NaN?以及正确解法

你的代码问题出在reduce的累加器类型不一致:
第一次执行reduce时,next是数组的第一个对象{name: "john", marks:50},number是第二个对象,你返回了next.marks + number.marks = 105——这个返回值会作为下一次执行时的next。第二次执行时,next已经是数字105了,它没有marks属性,所以next.marks就是undefined,加上number.marks(75)自然得到NaN。


正确写法1:指定初始累加值(推荐)

给reduce的第二个参数传入初始值0,让累加器始终保持数字类型,每次把当前对象的marks加到累加器上:

const obj = [
  { name: "john", marks: 50 },
  { name: "mary", marks: 55 },
  { name: "peter", marks: 75 },
];

const sum = obj.reduce((total, current) => {
  return total + current.marks;
}, 0); // 初始累加值为0

console.log(sum); // 输出180

正确写法2:不指定初始值(兼容累加器类型)

如果不想指定初始值,需要判断累加器的类型,兼容第一次累加器是对象的情况(这种写法不如第一种清晰):

const obj = [
  { name: "john", marks: 50 },
  { name: "mary", marks: 55 },
  { name: "peter", marks: 75 },
];

const sum = obj.reduce((total, current) => {
  const currentTotal = typeof total === 'object' ? total.marks : total;
  return currentTotal + current.marks;
});

console.log(sum); // 输出180

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 11:55:27