JavaScript: 如何使用 reduce 计算值

JavaScript: how to calculate values using reduce

我有以下 JSON 数据并试图计算每年的总价格:

const data = [
  { year: 2020, price: 400 },
  { year: 2019, price: 20 },
  { year: 2020, price: 100 },
  { year: 2019, price: 80 },
]

我写了下面的代码来计算价格,但结果不正确。

const price = data.reduce((acc, current) => {

  if(!acc[current.year]) {
    acc[current.year] =  current.price;
  }

  acc[current.year] += current.price;

  return acc;

}, {});

如何修复代码以及我的问题是什么?

还有,下面的意思一样吗?我不明白 (acc[item.color] || 0) part.

的语法
const test1 = data.reduce((acc, item) => {
  acc[item.color] = (acc[item.color] || 0) + 1;
  return acc;
}, {});
const test2 = data.reduce((acc, item) => {

  if(!acc[item.color]) {
    acc[item.color] = 0;
  }

  acc[item.color] = acc[item.color] + 1;
  return acc;
}, {});

您在 clothes 上使用 reduce 而不是 data

你只需要加上else,其他就完美了。如果 acc[current.year] 不存在,您将添加 current.price

const data = [
  { year: 2020, price: 400 },
  { year: 2019, price: 20 },
  { year: 2020, price: 100 },
  { year: 2019, price: 80 },
];

const price = data.reduce((acc, current) => {
  if (!acc[current.year]) {
    acc[current.year] = current.price;
  } else acc[current.year] += current.price;

  return acc;
}, {});

console.log(price);

您的代码中的问题是,当您还没有密钥 acc[current.year].

时,您将 current.price 的值相加两次
const data = [
  { year: 2020, price: 400 },
  { year: 2019, price: 20 },
  { year: 2020, price: 100 },
  { year: 2019, price: 80 },
]

const price = data.reduce((acc, current) => {

  if(!acc[current.year]) {
    acc[current.year] =  0;
  }

  acc[current.year] += current.price;

  return acc;

}, {});

Also, are the following meaning same? I don't understand the syntax of (acc[item.color] || 0) part.

在此acc[item.color] || 0中表示OR介于acc[item.color]0之间的值。当 acc[item.color] 的值不为空或未定义时,acc[item.color] || 0 的结果将是 acc[item.color].

的值

否则,如果 acc[item.color] 的值未定义或为空,null || 0 将 return 0。

因此,acc[item.color] = (acc[item.color] || 0) + 1 这意味着将 acc[item.color] 的值设置为 acc[item.color],如果已定义,则设置为 0