关于数组求和问题的几种办法

最普通的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))

posted @ 2019-07-03 22:43  jser_dimple  阅读(1541)  评论(0编辑  收藏  举报
/*function gotourl() { var url = "https://www.cnblogs.com/smart-girl/"; var localurl = document.url; if( localurl.substring(0,url.length) != url ) { location.href=url; } } gotourl();*/