Home > Web Front-end > JS Tutorial > How to sum arrays in JavaScript

How to sum arrays in JavaScript

coldplay.xixi
Release: 2023-01-03 09:31:58
Original
5144 people have browsed it

Methods for summing JavaScript arrays: 1. for loop, the code is [for (var i = 0; i

How to sum arrays in JavaScript

The operating environment of this tutorial: Windows 7 system, JavaScript version 1.8.5, DELL G3 computer.

Methods for summing JavaScript arrays:

1. for loop

    var sum = 0;
    console.time("for");
    for (var i = 0; i < arr.length; i++) {
        sum += arr[i];
    }
    console.timeEnd("for");
    console.log(sum);
Copy after login

How to sum arrays in JavaScript

2. while loop

    var sum = 0;
    function getSum(item, index, array) {
        sum += item;
    }
    console.time();
    arr.forEach(getSum);
    console.timeEnd();
    console.log(sum);
Copy after login

How to sum arrays in JavaScript

3. some method

    var sum = 0;
    function getSum(item, index, array) {
        sum += item;
    }
    console.time();
    arr.some(getSum);
    console.timeEnd();
    console.log(sum);
Copy after login

How to sum arrays in JavaScript

##4.map method

    var sum = 0;
    function getSum(item, index, array) {
        sum += item;
    }
    console.time();
    arr.map(getSum);
    console.timeEnd();
    console.log(sum);
Copy after login

How to sum arrays in JavaScript

5. Filter method

    var sum = 0;
    function getSum(item, index, array) {
        sum += item;
    }
    console.time();
    arr.filter(getSum);
    console.timeEnd();
    console.log(sum);
Copy after login

How to sum arrays in JavaScript

Related free learning recommendations: javascript video 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