P粉6814003072023-08-24 10:12:44
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粉9523651432023-08-24 09:15:31
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) )