比如说,在项目中遇见了数组对象里面的值,需要统计总和
let arr = [{
width: 155
}, {
width: 180
}, {
width: 180
}, {
width: 240
},
{
width: 130
}, {
width: 280
}, {
width: 100
}, {
width: 50
}
]
let result = arr.reduce((pre, cur, index) => {
let sum = Object.keys(pre).length > 0 ? pre[index - 1] + cur.width : 0 + cur.width;
pre[index] = sum;
return pre;
}, {})
console.log('result', result)