我有一系列产品,我想计算所有产品的总价格,但我不知道该怎么做。有什么建议吗?
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);
},
答案 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
});
}
//减少功能可以对产品的价格求和。