2 回答

TA貢獻1789條經驗 獲得超8個贊
如果您想要所有項目的總(總和)重量,您必須先獲得每個項目的重量,然后將它們加在一起。
const sum = (arr) => {
return arr.map(item => item.pieces * item.weight).reduce((current, total) => current + total)
}
let items = [{
id: 1,
label: 'test',
itemname: 'testitem',
pieces: 4,
weight: 0.02
},
{
id: 2,
label: 'test',
itemname: 'testitem',
pieces: 4,
weight: 0.02
},
{
id: 2,
label: 'test',
itemname: 'testitem',
pieces: 4,
weight: 0.02
}
]
const sum = (arr) => {
return arr.map(item => item.pieces * item.weight).reduce((current, total) => current + total)
}
const totalWeight = sum(items)
console.log(totalWeight)

TA貢獻1808條經驗 獲得超4個贊
您可以使用forEach循環遍歷數組,將pieces和weight值相加:
let pieces = 0; // sum of pieces
let weight = 0; // sum of weight
items.forEach(function(elmt){
pieces += elmt.pieces;
weight += elmt.weight;
});
然后乘以pieces* weight:
let total = pieces * weight;
console.log(total);
添加回答
舉報