JavaScript实现:数组之计算数组元素总和
题目描述: 计算给定数组 arr 中所有元素的总和
输入描述: 数组中的元素均为 Number 类型
e.g: 输入: [ 1, 2, 3, 4 ] ; 输出:10
答案一:
1 function sum(arr) { //不考虑算法复杂度,用递归做View Code
2 var len = arr.length;
3 if(len == 0){
4 return 0;
5 } else if (len == 1){
6 return arr[0];
7 } else {
8 return arr[0] + sum(arr.slice(1)); //arrayObject.slice(start,end)
9 }
10 }
链接:https://www.nowcoder.com/ta/js-assessment/来源:牛客网答案二: View Code链接:https://www.nowcoder.com/ta/js-assessment/来源:牛客网
1 function sum(arr) { //常规循环View Code
2 var s = 0;
3 for (var i=arr.length-1; i>=0; i--) {
4 s += arr[i];
5 }
6 return s;
7 }
链接:https://www.nowcoder.com/ta/js-assessment/
来源:牛客网
答案三:
1 function sum(arr) { //函数式编程 map-reduceView Code 答案四:
2 return arr.reduce(function(prev, curr, idx, arr){ //array1.reduce(callbackfn[, initialValue]);
3 return prev + curr; //function callbackfn(previousValue, currentValue, currentIndex, array1)
4 });
5 }
1 function sum(arr) { //forEach遍历View Code 链接:https://www.nowcoder.com/ta/js-assessment/
2 var s = 0;
3 arr.forEach(function(val, idx, arr) {
4 s += val;
5 }, 0);
6
7 return s;
8 };
来源:牛客网 答案五:
1 function sum(arr) {View Code 链接:https://www.nowcoder.com/ta/js-assessment/
2 return eval(arr.join("+"));
3 };
来源:牛客网