JavaScrip sum
时间: 2024-02-16 12:33:34 浏览: 47
To calculate the sum of an array in JavaScript, you can use the reduce() method.
For example, consider the following array:
```
const numbers = [1, 2, 3, 4, 5];
```
To find the sum of this array, you can call the reduce() method on the array and pass in a callback function that performs the summing operation:
```
const sum = numbers.reduce((accumulator, currentValue) => {
return accumulator + currentValue;
}, 0);
console.log(sum); // Output: 15
```
Here, the reduce() method takes two arguments: a callback function and an initial value for the accumulator. The callback function takes two arguments: the accumulator and the current value of the array element being processed. In this case, the function simply adds the current value to the accumulator. The initial value of the accumulator is set to 0.
阅读全文