对象的Javascript Reduce [重复]

mnemlml8  于 2023-01-04  发布在  Java
关注(0)|答案(1)|浏览(136)
    • 此问题在此处已有答案**:

Calling reduce to sum array of objects returns NaN(2个答案)
js - array .reduce returns NaN instead of calculated value [duplicate](2个答案)
Method reduce javascript [duplicate](3个答案)
reduce() method is returning NaN from an array of objects [duplicate](1个答案)
9小时前关闭.

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

我想用归约法计算总分。
我试过了-

const sum = obj.reduce((next, number) => {
  console.log("next", next.marks);
  console.log("number", number.marks);
  return next.marks + number.marks;
});

console.log(sum);

但是我得到的和是NaN总的结果是-

next 50
number 55
next undefined
number 75
NaN

我不知道为什么下一步是得到undefined之间。
如何通过reduce方法计算总和?

zi8p0yeb

zi8p0yeb1#

将默认值作为0传递给reduce

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

const sum = obj.reduce((acc, number) => {
  return acc+ number.marks;
}, 0);

console.log(sum)

相关问题