How to use ES6 methods to calculate the sum of an array?

You can utilize the reduce() method in ES6 to calculate the sum of an array.

const numbers = [1, 2, 3, 4, 5];
const sum = numbers.reduce((total, num) => total + num, 0);
console.log(sum); // 输出:15

In this example, the reduce() method takes two arguments: a callback function and an initial value. The callback function has two parameters: an accumulator and the current value. The return value of the callback function becomes the value of the accumulator for the next call to the callback function. The initial value parameter is optional and is used as the first argument for the initial call to the callback function before the iteration begins.

In this example, the initial value is 0. During each iteration, the callback function adds the current value to the accumulator and returns the new accumulator value. Ultimately, the reduce() method returns the final value of the accumulator, which is the total sum of the array.

The advantage of using ES6 methods for array summation is the concise code and the ability to better utilize JavaScript’s functional programming features.

bannerAds