Home > Web Front-end > JS Tutorial > How to implement accumulation in JavaScript

How to implement accumulation in JavaScript

藏色散人
Release: 2021-06-30 11:48:26
Original
5685 people have browsed it

JavaScript实现累加的方法:1、通过“for(var i=arr.length-1; i>=0; i--){...}”方式;2、通过“return arr.reduce(function(prev, curr){...}”方式等等。

How to implement accumulation in JavaScript

本文操作环境:windows7系统、javascript1.8.5版、Dell G3电脑。

JavaScript怎样实现累加?

用JS实现数组累加求和的4种方法

代码如下:

1,
function sum(arr) {
    var s = 0;
    for (var i=arr.length-1; i>=0; i--) {
        s += arr[i];
    }
    return s;
}
2,
function sum(arr) {
    return arr.reduce(function(prev, curr){
        return prev + curr;
    });
}
3,
function sum(arr) {
    var s = 0;
    arr.forEach(function(val) {
        s += val;
    });
  
    return s;
};
4,
function sum(arr) {
    return eval(arr.join("+"));
};
Copy after login

【相关推荐:javascript高级教程

The above is the detailed content of How to implement accumulation 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