How to find the sum of a set of numbers
P粉642920522
2023-08-23 11:40:32
<p>Given an array <code>[1, 2, 3, 4]</code>, how to find the sum of its elements? (In this example, the sum would be <code>10</code>.) </p>
<p>I think <code>$.each</code> might work, but I'm not sure how to implement it. </p>
That's exactly what does to
reduce
.If you are using ECMAScript 2015 (aka ECMAScript 6):
For older JS:
Isn’t this beautiful? :-)
Recommended (reduce by default)
Array.prototype.reduce Can be used to iterate over an array, adding the current element value to the sum of previous element values.