5 ways to Sum JS arrays

Source: Internet
Author: User
Tags eval

Title Description

Calculates the sum of all the elements in arr for a given array
Input Description:
The elements in the array are number types
Input Example:
SUM ([1, 2, 3, 4])
Output Example:

1, do not consider the complexity of the algorithm, using recursion to do:

function sum (arr) {    var len = arr.length;     if (len = = 0)        {return 0;     Else if (len = = 1)        {return arr[0]    ; Else {        return arr[0] + sum (arr.slice (1));}    }

2. General circulation

function sum (arr) {    var s = 0;      for (var i=arr.length-1; i>=0; i--) {        + = arr[i]    ;    } return s;}

3. Functional Programming Map-reduce

function sum (arr) {    return arr.reduce (function(prev, Curr, idx, arr) {         return prev + curr;    });

4. Foreach Traversal:

function sum (arr) {    var s = 0;    Arr.foreach (function(val, idx, arr) {        + = val    ; 0);       return s;};

5. Eval:

function sum (arr) {    return eval (arr.join ("+"));};

5 ways to Sum JS arrays

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.