每当我单击其下方的按钮时,就会调用populateGridWithSelectedData方法。
<Button variant="contained" color="primary" onClick= {this.populateGridWithSelectedData} >ADD</Button>
populateGridWithSelectedData(){
let items = [...this.state.items];
items.push({
invoiceLine: this.state.concatenatedInvoiceLine,
settledQuantity: this.state.settledQuantity,
price: this.state.unitPrice,
creditedQuantity: this.state.creditedQuantity,
reasonCode: this.state.reasonCode
});
this.setState({
items,
invoiceLine: '',
settledQuantity:'',
price:'',
creditedQuantity:'',
reasonCode:''
});
}
我正在将数据推入数组。这可能是很多数据。 我希望能够在每次推送时执行以下操作
这似乎不起作用。
var total = 0;
var multipliedResult = 0;
for (var x in items){
multipliedResult = (price * creditedQuantity);
total = (total + multipliedResult);
}
我在做什么错?
答案 0 :(得分:0)
for in
循环用于对象。您有一个数组。您正在寻找for of
for (var x of items){
multipliedResult = (price * creditedQuantity);
total = (total + multipliedResult);
}
答案 1 :(得分:0)
您正在使用一个数组,但没有使用该数组的任何值。您有两个选择-遍历数组长度的普通for
循环:
for (var x = 0; x < items.length; x++) {
multipliedResult = price * creditedQuantity;
total += multipliedResult;
}
或没有参数的forEach
循环:
items.forEach(() => {
multipliedResult = price * creditedQuantity;
total += multipliedResult;
})
答案 2 :(得分:0)
这可能更好:
var total = 0;
items.forEach(item => {
let multipliedResult = (item.price * item.creditedQuantity)
total += multipliedResult
})