我有一个表示客户购买的物品的数组,并在此逻辑中计算了物品小计:
function getSubtotal(arr) {
let total = 0.00;
arr.forEach(function(i) {
total += (i.qty * i.price)
});
return total; // 1274.21
}
是的,当然我得到了正确的结果,但是在 javascript 中有什么有效的方法可以做到这一点吗?
let data = [
{
name : 'Item 1', qty: 2, price: 15.50 // 31
},
{
name : 'Item 2', qty: 17, price: 25.13 // 427.21
},
{
name : 'Item 3', qty: 102, price: 8.00 // 816
}
];
function getSubtotal(arr) {
let total = 0.00;
arr.forEach(function(i) {
total += (i.qty * i.price)
});
return total; // 1274.21
}
document.write(getSubtotal(data));
我想编辑@FrankCamara 的答案,但不能。所以这里有不同的格式:
这是一种简单的方法,使用reduce。
let data = [
{
name : 'Item 1', qty: 2, price: 15.50 // 31
},
{
name : 'Item 2', qty: 17, price: 25.13 // 427.21
},
{
name : 'Item 3', qty: 102, price: 8.00 // 816
}
];
function getSubTotal (items) {
const fn = (total, { price, qty }) => total + price * qty;
return items.reduce(fn, 0);
}
console.log(getSubTotal(data));
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句