=0; i--){...}"; 2. Through "return arr.reduce(function(prev , curr){...}" method and so on."/> =0; i--){...}"; 2. Through "return arr.reduce(function(prev , curr){...}" method and so on.">

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

How to implement accumulation in JavaScript

藏色散人
藏色散人Original
2021-06-30 11:48:265649browse

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("+"));
};

【相关推荐: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!

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