Title Description
Calculates the sum of all the elements in arr for a given array
Input Description:
The elements in the array are number types
Input Example:
SUM ([1, 2, 3, 4])
Output Example:
10
1, do not consider the complexity of the algorithm, using recursion to do:
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));} }
2. General circulation
function sum (arr) { var s = 0; for (var i=arr.length-1; i>=0; i--) { + = arr[i] ; } return s;}
3. Functional Programming Map-reduce
function sum (arr) { return arr.reduce (function(prev, Curr, idx, arr) { return prev + curr; });
4. Foreach Traversal:
function sum (arr) { var s = 0; Arr.foreach (function(val, idx, arr) { + = val ; 0); return s;};
5. Eval:
function sum (arr) { return eval (arr.join ("+"));};
5 ways to Sum JS arrays