计算价格总和

Calculating sum of price

本文关键字:计算      更新时间:2023-09-26

我有一系列产品,我想计算所有产品的总价,但我不知道该怎么做。有什么建议吗?

 CountTotal: function() {
            var total;
            var totalsum;
            this.state.data.forEach(function(item, index) {
              total += item.price + item.quantity;
              totalsum += total + index.length;
            });
              console.log(totalsum);
          },
 CountTotal: function() {
            var total;
            this.state.data.forEach(function(item, index) {
              total += item.price * item.quantity;
            });
            console.log(total);
          },

或与Array#reduce

 CountTotal: function() {
            var total = this.state.data.reduce(function(res,item) {
              return res + (item.price * item.quantity);
            }, 0);
            console.log(total);
          },
handleQuantityChange = id => {
    const carsSelected = this.state.selectedProducts;
    var totalPrice= this.state.selectedProducts.reduce(function(res,item) {
              return res + item.price;
            }, 0);
    const oldTotal = this.state.totalPrice
    const newPrice = id.price + oldTotal
    this.setState({
      selectedProducts: [...carsSelected, id],
      totalPrice: totalPrice
    });
  }
/

/reduce函数可以对产品的价格求和。