Add sums of array. Display one output

前端 未结 3 393
被撕碎了的回忆
被撕碎了的回忆 2021-01-26 01:02

Update: The answer to this question is bellow. Thanks to dougtesting on a different thread. add array together, display sum

function hello() {
    var arr = [];
         


        
3条回答
  •  自闭症患者
    2021-01-26 01:31

    This is probably one of the simplest examples of something that Javascript's built in array .reduce() function would be used for. Effectively, you're "reducing an array to a single value".

    A reduce works by taking an array and running a function on each item. This "callback" function receives the value that the previous function returns, processes it in some way, then returns a new value. Worth noting, the reduce function also takes a 2nd argument that acts as the initial value that will be passed to the callback function the first time.

    array.reduce(callbackFunction, initialValue);
    

    Here's an example of reduce being used to sum an array.

    var result = [1,2,3,4,5,6,7,8,9,10].reduce(function(accumulator, currentValue) {
      return accumulator + currentValue;
    }, 0); // start with an initial value of 0
    console.log(result);

    Using ES6 syntax, this can be further simplified to a one-liner

    var result = [1,2,3,4,5,6,7,8,9,10].reduce((accumulator, currentValue) => accumulator + currentValue, 0);
    console.log(result);

提交回复
热议问题