为什么我不能减少数组?

Why I cannot reduce an array?

如果有人能向我解释为什么当我想获得金额总和时我总是得到类似这样的错误,我会很高兴:"Operator + 不能应用于类型“{ data: string, amount: number}” 或任何其他类型。


const payments = [
      [
        { data: '11/12/19', amount: 1000 },
      ],
      [
        { data: '11/01/20', amount: 1000 },
        { data: '12/01/19', amount: 1000 },
      ],
      [],
      [
        { data: '11/02/20', amount: 1000 },
        { data: '12/02/19', amount: 1000 },
        { data: '12/02/19', amount: 1000 },
      ],
      [],
      [],
      [],
      [],
      [],
      [],
      [],
      [],
    ];

    const acc = new Array(12).fill([]);

    acc.forEach((value, index, arr) => {
      if (payments[index] === undefined) { return []; }
      console.log(payments[index]);
      const total = payments[index].reduce((acc, value) => acc + value.amount)
    });


如果不向.reduce传递第二个参数,它的初始值将是数组中的第一项。但是你的数组项是对象,对象不能用 .amount(一个数字)+ed。相反,给它一个初始值 0:

const total = payments[index].reduce((acc, value) => acc + value.amount, 0)

您还应该在 acc 中创建 12 个 单独的 数组,而不是创建一个出现 12 次的数组:

const acc = new Array(12).fill().map(() => []);

否则,更改 acc 中的任何数组都会更改所有数组。

这里的问题是 reduce() 试图将一个对象和一个数字相加,而正在减少的数组中有多个对象。

发生这种情况是因为没有提供 "starting value" 供您减少。当没有提供起始值时,reduce 将获取数组的第一项,并将后续项累加到该项(基于您的归约逻辑),在您的情况下,这会导致类似这样的事情发生:

{ data: '11/01/20', amount: 1000 } + 1000 // Invalid

对于您的情况,可以通过提供 0 作为 reduce() 的第二个参数(表示总计的起始值)来解决问题。对您的代码进行以下修改(以及其他简化)应该可以解决问题:

const payments = [
      [
        { data: '11/12/19', amount: 1000 },
      ],
      [
        { data: '11/01/20', amount: 1000 },
        { data: '12/01/19', amount: 1000 },
      ],
      [],
      [
        { data: '11/02/20', amount: 1000 },
        { data: '12/02/19', amount: 1000 },
        { data: '12/02/19', amount: 1000 },
      ],
      [],
      [],
      [],
      [],
      [],
      [],
      [],
      [],
    ]
    // Transform the payments array to a collection of totals using map
    .map((payment) => {
  
      // Pass 0 as starting value for sum calculation of the current
      // payment array
      return payment.reduce((total, item) => total + item.amount, 0);
    });

console.log(payments);

希望对您有所帮助!