简体   繁体   中英

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.一只忙碌的猫

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

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 .

Complete working example find out here in this StackBlitz Link

You just need to calculate cart amount using reduce() array function.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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