In the previous article, we learned about how to create an array with a variable number. Please see "How to create an array with a variable number in js". This time we will take a look at how to achieve the cumulative effect of elements in an array. You can refer to it if necessary.
First let’s look at a small example.
We now have such a problem. It is known that we have an array containing four elements, 1, 2, 3, and 4. Now we want to know the sum of the elements in this array and how to calculate it. Woolen cloth? What if we add the element two? Does this still add up to the same amount?
<script> var arr = new Array(7); arr[0] = 1; arr[1] = 2; arr[2] = 3; arr[3] = 4; console.log(arr); const reducer = (accumulator, currentValue) => accumulator + currentValue; console.log(arr.reduce(reducer)); var nums = new Array(7); nums[0] = 1; nums[1] = 2; nums[2] = 3; nums[3] = 4; nums[4] = "two"; console.log(nums); console.log(nums.reduce(reducer)); </script>
The result of this small example is
We can observe the result based on the question, the four elements 1, 2, 3, and 4 are accumulated The result of adding up is 10, and the cumulative result of the five elements 1, 2, 3, 4 and two is 10two. This shows that in this method, if English appears, the English will not be filtered and will be directly operated with numbers.
After understanding so much, let’s take a look at this method in detail. The
reduce() method executes a reducer function provided by us (executed in ascending order) on each element in the array, and summarizes the results into a single return value.
Let’s take a look at the syntax of this method.
数组名称.reduce(执行的函数(累计器的返回值,正在处理的元素,当前元素索引,数组,第一次调用函数时的值)
reduce executes the callback function for each element in the array in turn, excluding elements that are deleted or never assigned a value in the array, and accepts four parameters:
accumulator Accumulator
currentValue current value
currentIndex current index
array array
Note: If the value when the function is called for the first time is not provided, reduce will execute the callback method starting from index 1, skipping the first index. If a value is provided when the function is first called, it starts at index 0.
That’s all. If you need it, you can read: javascript basic tutorial
The above is the detailed content of How to achieve the cumulative effect of elements in js array. For more information, please follow other related articles on the PHP Chinese website!