This article mainly introduces the common methods of JS array summation, and summarizes and analyzes 5 common operation methods and related processing techniques of array summation in the form of examples. Friends in need can refer to the following
The examples in this article summarize the common methods of summing JS arrays. Share it with everyone for your reference, the details are as follows:
Problem description
Calculate the sum of all elements in the given array arr
Input description:
The elements in the array are all of type Number
Input example:
sum([ 1, 2, 3, 4 ])
result:
10
Method 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));
}
}
Method 2. Regular circulation:
function sum(arr) {
var s = 0;
for (var i=arr.length-1; i>=0; i--) {
s += arr[i];
}
return s;
}
Method 3. forEach omnibus:
function sum(arr) {
var s = 0;
arr.forEach(function(val, idx, arr) {
s += val;
}, 0);
return s;
};
character4. eval:
function sum(arr) {
return eval(arr.join("+"));
};
Method 5. Functional programming map-reduce:
function sum(arr) {
return arr.reduce(function(prev, curr, idx, arr){
return prev + curr;
});
}
Test output running result:
console.log(sum([ 1, 2, 3, 4 ]))
Source: https://www.jb51.net/article/154559.htm