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

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

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

上一篇:【POJ 1845】Sumdiv&&【洛谷 P1593】因数和


下一篇:力扣(LeetCode)两整数之和 个人题解