How to sum the elements in an array in JS

藏色散人
Release: 2018-12-22 16:57:50
Original
17660 people have browsed it


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.

How to sum the elements in an array in JS

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>
Copy after login

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:

How to sum the elements in an array in JS

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template