How to find the sum of a set of numbers
P粉642920522
P粉642920522 2023-08-23 11:40:32
0
2
492
<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>
P粉642920522
P粉642920522

reply all(2)
P粉681400307

That's exactly what does to reduce .

If you are using ECMAScript 2015 (aka ECMAScript 6):

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

For older JS:

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 this beautiful? :-)

P粉952365143

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.

console.log(
  [1, 2, 3, 4].reduce((a, b) => a + b, 0)
)
console.log(
  [].reduce((a, b) => a + b, 0)
)
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template