JavaScript 中超过 2 项的键的对象总和数组返回 NaN

Sum array of object of a key is returning NaN for more than 2 items in JavaScript

以下是我的数组-

const products = [{
  id: "1",
  quantity: 3
}, {
  id: "2",
  quantity: 3
}]

console.log(products.reduce((acc, product) => acc.quantity + product.quantity)) // 6 -> Correct

但是,如果数组包含超过 2 个项目,它就会抛出 NaN 结果,让我知道我在这里做错了什么。

const products = [{
  id: "1",
  quantity: 3
}, {
  id: "2",
  quantity: 3
}, {
  id: "3",
  quantity: 4
}]
console.log(products.reduce((acc, product) => acc.quantity + product.quantity)) // NaN -> InCorrect

默认情况下,累加器的初始值是数组中的第一个元素。如果第一个元素是一个 object,那么向该对象添加任何东西都会导致 NaN.

只需向 reduce 提供另一个参数以提供累加器的初始值,并确保累加器记录 sum:

const products = [{
  id: "1",
  quantity: 3
}, {
  id: "2",
  quantity: 3
}, {
  id: "3",
  quantity: 4
}];

const total = products.reduce((acc, product) => acc + product.quantity, 0);
console.log(total);

如果您真的希望让累加器存储一个对象,您可以这样做,但它会改变数组中的第一个元素,您必须确保访问适当的 属性 以记录它:

const products = [{
  id: "1",
  quantity: 3
}, {
  id: "2",
  quantity: 3
}, {
  id: "3",
  quantity: 4
}]
console.log(products.reduce((acc, product) => {
  acc.quantity += product.quantity;
  return acc;
}).quantity) 

但那是一个真的坏主意。

因为acc第二次是6,acc.quantity未定义。要解决此问题,请将 acc.quantity 替换为 acc 并使用 0 作为起始累加器

reduce() 方法对累加器和数组中的每个元素(从左到右)应用函数以将其减少为单个值。

在您的 acc 变量中,它包含值而不是对象,您可以像这样直接添加新数量

演示版

const products = [{
  id: "1",
  quantity: 3
}, {
  id: "2",
  quantity: 3
}, {
  id: "3",
  quantity: 4
}];

let result = products.reduce((acc, {quantity}) => acc +quantity, 0);

console.log(result)
.as-console-wrapper {  max-height: 100% !important;  top: 0;}

This works perfectly fine

<script>
       const products = [{id: "1", quantity: 3},{id: "2", 
       quantity: 3},{id: "3", quantity: 4}];  

       total = Object.values(products).reduce((t, n) => t       
      + n.quantity, 0);

    console.log(total);
    </script>