Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
146 views
in Technique[技术] by (71.8m points)

javascript - 如何找到数字数组的总和(How to find the sum of an array of numbers)

Given an array [1, 2, 3, 4] , how can I find the sum of its elements?

(给定一个数组[1, 2, 3, 4] ,我如何找到它的元素之和?)

(In this case, the sum would be 10 .)

((在这种情况下,总和为10 ))

I thought $.each might be useful, but I'm not sure how to implement it.

(我认为$.each可能有用,但是我不确定如何实现它。)

  ask by akano1 translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

In Lisp , this'd be exactly the job for reduce .

(在Lisp中 ,这正是reduce工作量的工作。)

You'd see this kind of code:

(您会看到以下代码:)

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

Fortunately, in JavaScript, we also have reduce !

(幸运的是,在JavaScript中,我们也有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:

(如果您使用的是ECMAScript 2015(又名ECMAScript 6 ),它可能会很漂亮:)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...