Home > Web Front-end > JS Tutorial > body text

How to sum arrays in javascript

青灯夜游
Release: 2023-01-05 16:07:44
Original
14460 people have browsed it

Summing method: 1. Use recursion to add the elements in the array one by one to sum; 2. Use for loop to add the elements in the array one by one to sum; 3. Use forEach to traverse , add the elements in the array one by one to calculate the sum; 4. Use eval() and join(), the syntax is "eval(arr.join(" "))".

How to sum arrays in javascript

The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.

Title description

Calculate the sum of all elements in the given array arr

Input description:
数组中的元素均为 Number 类型
Copy after login
Input example:
sum([ 1, 2, 3, 4 ])
Copy after login
Output example:
10
Copy after login

1. Regardless of algorithm complexity, use recursion:

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));
    }
}
Copy after login

2. Regular loop

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

3. forEach traversal:

function sum(arr) {
    var s = 0;
    arr.forEach(function(val, idx, arr) {
        s += val;
    }, 0);
  
    return s;
};
Copy after login

4. eval:

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

[Recommended learning: javascript advanced tutorial]

The above is the detailed content of How to sum arrays in javascript. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template