To sum the elements in a JS array, we can use the reduce() method to find or calculate the sum of the numeric array. The reduce() method executes the specified reducer function on each member of the array, producing a single output value.
Now we will introduce to you the implementation method of summing elements in JS array based on specific code examples.
The code example is as follows:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>JS计算数组元素总和</title> </head> <body> <script> var array = [1, 2, 3, 4, 5]; // 求数组元素总和 var sum = array.reduce(function(a, b){ return a + b; }, 0); document.write(sum); </script> </body> </html>
The 0 in the above example is the initialValue, which is the value (initial value) used as the first call parameter of the callback. If no initial value is provided, the first element in the array will be used.
If the array is empty and no initial value is provided, an error will be thrown. Therefore, if you want to do addition, you need to provide an initial value, such as 0. If you want to do multiplication, you also need to provide an initial value, such as 1.
The calculation results are as follows:
reduce() The method receives a function as an accumulator, and each value in the array (from left to right) starts to reduce and finally calculates to a value.
reduce() can be used as a higher-order function for compose of functions.
Note: reduce() will not execute the callback function for an empty array.
This article is an introduction to the method of summing elements in a JS array. It is very simple. I hope it will be helpful to friends in need!
The above is the detailed content of How to sum the elements in an array in JS. For more information, please follow other related articles on the PHP Chinese website!