js 数组中挨个数字相加如何做?

let data = {}
let arr = [
    { width: 155 }, { width: 180 }, { width: 180 }, { width: 240 },
    { width: 130 }, { width: 280 }, { width: 100 }, { width: 50 }
]
for (let j = 0; j < arr.length; j++) {
    if (j >= 1) {
      console.log(j - 1, j)
      data[j] = arr[j] = [j - 1].with + arr[j] = [j].with
    }
  }
如何做到
data {    0: arr[0] + arr[1],    1: arr[0] + arr[1] + arr[2],    2: arr[0] + arr[1] + arr[2] + arr[3] 
    ......
}


皈依舞
浏览 2408回答 1
1回答

梵蒂冈之花

let&nbsp;data&nbsp;=&nbsp;arr.reduce((sum,&nbsp;cur,&nbsp;index)&nbsp;=>&nbsp;{&nbsp;&nbsp;sum[index]&nbsp;=&nbsp;index&nbsp;===&nbsp;0&nbsp;?&nbsp;cur.width&nbsp;:&nbsp;sum[index&nbsp;-&nbsp;1]&nbsp;+&nbsp;cur.width&nbsp;&nbsp;return&nbsp;sum},&nbsp;{})
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript