Creating an array of cumulative sum in javascript

后端 未结 21 1629
时光取名叫无心
时光取名叫无心 2020-11-27 06:23

This is an example of what I need to do:

var myarray = [5, 10, 3, 2];

var result1 = myarray[0];
var result2 = myarray[1] + myarray[0];
var result3 = myarray         


        
21条回答
  •  半阙折子戏
    2020-11-27 07:04

    Old school and simpler :

    let myarray = [5, 10, 3, 2], result = [];
    
    for (let i = 0, s = myarray[0]; i < myarray.length; i++, s += myarray[i]) result.push(s);
    
    console.log(result); // [5, 15, 18, 20]
    

提交回复
热议问题