Creating an array of cumulative sum in javascript

后端 未结 21 1496
时光取名叫无心
时光取名叫无心 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:17

    /*Checkout the explanation below */

    nums = [1,2,3,4]
    var runningSum = function(nums) { 
    shoppingCart =[];
    runningtotal =0;  
    nums.forEach(EachValue => {  
    runningtotal += EachValue
    shoppingCart.push(runningtotal);  
    });
    return shoppingCart       
    };
    
    console.log(runningSum(nums));
    

    /* define some numbers*/

    nums = [1,2,3,4]
    

    /* assign function runningSum , some numbers*/

    var runningSum = function(nums) { 
    shoppingCart =[]; /* Create a empty shopping cart to store the items */
    runningtotal =0;  /* Start with your beginning bill of zero items in the cart */
    

    /* remove a number from list of numbers call each one of the numbers from the array => EachValue using a pointer function*/

    nums.forEach(EachValue => {  
    
             (runningtotal += EachValue) 
    

    /* Now add the value to the runningtotal to represent items prices*/

    shoppingCart.push(runningtotal);  
    

    /* Use the push method to place it into the new array called shopping cart */ });

    return shoppingCart

    /* output the items currently in the shopping cart with only 1d prices */

    };

        nums = [1,2,3,4]
        var runningSum = function(nums) { 
        shoppingCart =[];
        runningtotal =0;  
        nums.forEach(EachValue => {  
        runningtotal += EachValue
        shoppingCart.push(runningtotal);  
        });
        return shoppingCart       
        };
    
        console.log(runningSum(nums));

提交回复
热议问题