JavaScript:如何使用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) 部分的语法。

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,其他一切都很完美。如果current.price不存在,则acc[current.year]正在添加。

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

另外,以下含义是否相同?我不明白 (acc[item.color] || 0) 部分的语法。

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

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

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

最新更新