简体   繁体   English

添加购物车中产品的总和

[英]Add Sum total of Products in a Cart

I have a rookie problem, and that is adding the sum total from an object (Cart) in my cart page before I go check out.我有一个新手问题,那就是在我 go 结帐之前,在我的购物车页面中添加 object(购物车)的总和。一只忙碌的猫

Every time I navigate from one screen to the other the amount keeps going up每次我从一个屏幕导航到另一个屏幕时,数量都会不断增加一只忙碌的猫 2

I want the total amount to be 159, or the correct amount if i add more products我希望总金额为 159,或者如果我添加更多产品,则为正确的金额

SourceCode 源代码

Try to replace this piece of code:尝试替换这段代码:

this.cartItems.forEach((value, index) => {
    this.totalAmount += parseInt(value.amount);
});

with this:有了这个:

this.totalAmount = this.cartItems.reduce((acc, item) => {
    return acc += item.amount;
}, 0);

In the first case you add a new value to already existing value.在第一种情况下,您向现有值添加一个新值。 And in the reduce version it should rewrite the totalAmount .reduce版本中,它应该重写totalAmount

Complete working example find out here in this StackBlitz Link完整的工作示例在此StackBlitz 链接中找到

You just need to calculate cart amount using reduce() array function.您只需要使用 reduce() 数组 function 来计算购物车数量。

this.total = this.cart.reduce( (acc,curVal) => {
    return acc + (curVal.amount * curVal.quantity); 
     //this.temp.push( curVal.amount * curVal.quantity);
  },0)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM