最普通的for循环
(function(){
var arr1 = [1,2,3,4,5],
arr2 = [3,5,6,6],
sum = 0;
var getSum = function(ar){
arr = ar
for(i = 0;i<arr.length;i++){
sum = sum + arr[i]
}
return sum;
}
alert(getSum(arr2))
})()
函数式编程 map-reduce
var arr1 = [1,2,3,5]
var getSum = function(ar){
var arr =ar
var sum = arr.reduce(function(prev,curr,index,arr){
return prev + curr;
})
return sum;
}
alert(getSum(arr1))
forEach迭代
var arr1 = [1,2,3,5]
var getSum = function(ar){
var arr = ar;
var s = 0;
arr.forEach(function(val,index,arr){
s = s+val;
},0)
return s;
}
alert(getSum(arr1))
eval方法
var arr1 = [1,2,3,5]
var getSum = function(ar){
var arr = ar;
var s = eval(arr.join("+"))
return s;
}
alert(getSum(arr1))