How to find the sum of an array of numbers

后端 未结 30 2596
醉话见心
醉话见心 2020-11-21 13:36

Given an array [1, 2, 3, 4], how can I find the sum of its elements? (In this case, the sum would be 10.)

I thought $.each might be useful,

30条回答
  •  借酒劲吻你
    2020-11-21 14:11

    In Lisp, this'd be exactly the job for reduce. You'd see this kind of code:

    (reduce #'+ '(1 2 3)) ; 6
    

    Fortunately, in JavaScript, we also have reduce! Unfortunately, + is an operator, not a function. But we can make it pretty! Here, look:

    const sum = [1, 2, 3].reduce(add,0); // with initial value to avoid when the array is empty
    
    function add(accumulator, a) {
        return accumulator + a;
    }
    
    console.log(sum); // 6
    

    Isn't that pretty? :-)

    Even better! If you're using ECMAScript 2015 (aka ECMAScript 6), it can be this pretty:

    const sum = [1, 2, 3].reduce((partial_sum, a) => partial_sum + a,0); 
    console.log(sum); // 6
    

提交回复
热议问题