我是编码的新手,所以这可能是一个简单的问题,但我无法理解。我有一组所有的最好的馅饼,每个都有自己的价格:
pieArr = [blueberry, strawberry, pumpkin, apple]
我想创建一个对象数组,根据饼图的价格显示购物车的总量,并且这里有人建议我使用reduce。
这是我到目前为止所拥有的:
var total = 0;
const totalArr = pieArr.reduce((totalPrice, pie) => {
if ( pie === "blueberry") {
total += 2.5;
totalPrice.push({["cartTotal"]:total});
return totalPrice;
}
else if (pie === "apple") {
total += 2;
totalPrice.push({["cartTotal"]:total});
return totalPrice;
},
[])};
我希望最终结果是一个新的对象数组,并不断添加新的总数:
[{cartTotal:2.5},{cartTotal:4.5}]
创建了新的对象数组,但是总和没有被累加,因此两次的总和都是0:
[{cartTotal: 0},{cartTotal: 0}]
我在做什么错了?
答案 0 :(得分:4)
执行此操作的一种好方法是进行价格查询:
pipe(
take(this.count),
map(() => {
--this.count;
return this.count;
})
然后,您可以在let piePrices = {
blueberry: 2.25,
strawberry: 1.5,
pumpkin: 3,
apple: 2
}
噪声中使用它(如果您只是从一个数组中创建一个数组,它比map()
更好):
reduce()
答案 1 :(得分:0)
const total = 0;
let pieArr = ['blueberry', 'strawberry', 'pumpkin', 'apple']
const totalArr = pieArr.reduce((totalPrice, pie) => {
let foundPie = totalPrice.find(x => x.name === pie) || {name: pie, total: 0};
if ( pie === "blueberry") {
foundPie.total += 2.5;
}
else if (pie === "apple") {
foundPie.total += 2;
}
if(!totalPrice.some(x=>x.name === pie)){
totalPrice.push(foundPie)
}
return totalPrice;
}, []);
console.log(totalArr)
我建议添加另一个属性name
,以使图片更清晰。在我们reducing
的同时,从累积的totalPrice
数组中找到派,然后进行求和,并检查是否将元素推送到累积的数组中