关于数组求和问题的几种办法
1、最普通的for循环
1 (function(){ //最外层函数是一个立即执行的匿名函数,此处不是必须的,不懂的可以去了解一下函数的闭包 2 3 var arr1=[1,2,3,5], //数组1 4 arr2=[3,5,6,6], 5 sum=0; 6 var getsum=function(ar){ 7 arr=ar 8 for (i=0;i<arr.length ;i++ ) 9 { 10 sum+=arr[i]; 11 } 13 return sum; 14 } 15 alert(getsum(arr2)) 16 17 })(); 18
2.函数式编程map-reduce
1 var arr1=[1,2,3,5]; 2 var getSum=function(ar){ 3 var arr=ar 4 var sum=arr.reduce(function(prev, curr, idx, arr){ 5 return prev + curr; 6 }) 7 return sum; 8 } 9 alert( getSum(arr1)); //11
3 、forEach迭代:
1 var arr1=[1,2,3,5]; 2 var getSum=function(ar){ 3 var arr=ar; 4 var s = 0; 5 arr.forEach(function(val, idx, arr) { 6 s += val;}, 0); 7 8 return s; 9 10 }; 11 alert(getSum(arr1)); //11
4、eval方法:
1 var arr1=[1,2,3,5]; 2 var getSum=function(ar){ 3 var arr=ar; 4 var s=eval(arr.join("+")) 5 6 return s; 7 8 }; 9 alert( getSum(arr1));