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

How to sum arrays in JavaScript

coldplay.xixi
coldplay.xixiOriginal
2021-03-31 10:08:465107browse

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);

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);

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);

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);

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);

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!

Statement:
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

Related articles

See more