www.webdeveloper.com
Results 1 to 3 of 3

Thread: I dont understand javascript array sum

  1. #1
    Join Date
    Aug 2017
    Posts
    6

    I dont understand javascript array sum

    I dont understand what happend in this code.

    <!DOCTYPE html>
    <html>
    <body>

    <p>Click the button to get the sum of the numbers in the array.</p>
    <button onclick="myFunction()">Try it</button>

    <p>Sum of numbers in array: <span id="demo"></span></p>

    <script>
    var numbers = [65, 44, 12, 4];

    function getSum(total, num) {
    return total + num;
    }
    function myFunction(item) {
    document.getElementById("demo").innerHTML = numbers.reduce(getSum);
    }
    </script>

    </body>
    </html>

    What happend in function getSum and what in myFunction? Source is w3schools

  2. #2
    Join Date
    Mar 2007
    Location
    localhost
    Posts
    5,762
    My suggestion is to read up what the function method reduce() does...

    In simple terms, you use the .reduce() on an array and its parameter is a function that is used against the array of element

    You could look at it like this, it reduces the array length by 1 each iteration until it is zero length and quits the function call.

    Each time the array is encountered, the array[0] and array[1] are added together (if it exists) and the result is stored in the 1st array element for the next iteration.

    Eventually the function completes and out pops your answer.
    --> JavaScript Frameworks like JQuery, Angular, Node <--
    ... and please remember to wrap code with forum BBCode tags:-

    [CODE]...[/CODE] [HTML]...[/HTML] [PHP]...[/PHP]

    If you can't think outside the box, you will be trapped forever with no escape...

  3. #3
    Join Date
    Mar 2007
    Location
    localhost
    Posts
    5,762
    Also, when posting code, please use the forum BB Code tags, see my signature for a link and for examples of types.
    --> JavaScript Frameworks like JQuery, Angular, Node <--
    ... and please remember to wrap code with forum BBCode tags:-

    [CODE]...[/CODE] [HTML]...[/HTML] [PHP]...[/PHP]

    If you can't think outside the box, you will be trapped forever with no escape...

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center

"

"