Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
392 views
in Technique[技术] by (71.8m points)

javascript - 为什么我不能减少数组?(Why I cannot reduce an array?)

I would be glad if anyone could explain to me why when I want to get a sum of amounts I always get an error something like: "Operator + cannot be applied to types '{ data: string, amount: number}' or any other type.

(如果有人能向我解释为什么我想得到一定数量的总和,我总是很高兴,但是总会出现类似以下错误: “运算符+无法应用于类型'{数据:字符串,数量:数字}'或任何其他类型类型。)


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)
    });


  ask by Valary o translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you don't pass a second parameter to .reduce , its initial value will be the first item in the array.

(如果不向.reduce传递第二个参数,则其初始值将是数组中的第一项。)

But your array items are objects, and objects can't be + ed with .amount (a number).

(但是,你的阵列项目是对象,对象不能是+与ED .amount (数字)。)

Instead, give it an initial value of 0:

(而是给它一个初始值0:)

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

You also should probably create 12 separate arrays in your acc , rather than creating a single array that's present 12 times:

(您可能还应该在acc创建12个单独的数组,而不是创建一个存在12次的单个数组:)

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

Otherwise, changing any array inside acc will change all of them.

(否则,更改acc内部的任何数组将更改所有数组。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...