前端数组对象合计某个金额字段
可以使用reduce方法来对数组对象的某个金额字段进行合计。
假设有以下数组对象:
const items = [
{ name: 'item1', price: 100 },
{ name: 'item2', price: 200 },
{ name: 'item3', price: 300 }
];
要合计这些对象中的price字段,可以使用reduce方法:
const totalPrice = items.reduce((acc, item) => acc + item.price, 0);
console.log(totalPrice); // 输出600
在上述代码中,reduce方法接收两个参数:一个回调函数和一个初始值。回调函数接收两个参数:累加器(acc)和当前值(item)。初始值为0。在每次迭代中,回调函数将当前值的price字段加到累加器上,最终得到合计金额。
原文地址: https://www.cveoy.top/t/topic/iKEQ 著作权归作者所有。请勿转载和采集!