关于数组求和问题的几种办法
最普通的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))
作者:jser_dimple
-------------------------------------------
个性签名:一个人在年轻的时候浪费自己的才华与天赋是一件非常可惜的事情
如果觉得这篇文章对你有小小的帮助的话,记得在右下角点个“推荐”哦,博主在此感谢!
万水千山总是情,打赏5毛买辣条行不行,所以如果你心情还比较高兴,也是可以扫码打赏博主,哈哈哈(っ•̀ω•́)っ✎⁾⁾!
微信
支付宝