计算价格总和

时间:2016-03-09 13:51:21

标签: javascript arrays

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

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

2 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:0)

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

//减少功能可以对产品的价格求和。