Detailed explanation of the principle and usage of javascript reduce function

PHPz
Release: 2023-04-24 10:20:50
Original
1704 people have browsed it

The reduce function is a very commonly used function in Javascript, which can greatly simplify our operations on arrays. In this article, we will explain in detail how the reduce function works and how to implement it.

1. The concept of reduce function

The reduce function is a very important function in Javascript. It is often used to process arrays. Its role is to summarize all elements in the array into a single value through a specified function. The syntax of the reduce function is as follows:

array.reduce(function(total, currentValue, currentIndex, arr), initialValue)
Copy after login

Where:

  • total is the accumulator value we want to return.
  • currentValue, which is the current value.
  • currentIndex, the current index.
  • arr, the array itself.
  • initialValue, the initial value.

The core idea of ​​the reduce function is "induction", that is, "fusion" of all elements together in some way. Typically, we can use it to calculate the sum, product, average, etc. of array elements.

2. Implementation of the reduce function

In Javascript, we can simulate the implementation of the reduce function through loops. Specifically, we can use the following method:

  1. Define the accumulator variable total

First, we need to define an accumulator variable total, which will store the reduce function The final result returned.

  1. Traverse the array elements

Then, we need to traverse the array elements and operate on each element. During the traversal process, we need to take out the current element and current index value for use in subsequent operations.

  1. Call the callback function

In the process of each traversal, we need to call the callback function. The callback function accepts 4 parameters: the accumulator variable total, the current element currentValue, the current index value currentIndex, and the entire array arr. The core logic of the callback function is to update the value of the accumulator variable total.

  1. Return the accumulator variable

After traversing all the elements, we need to return the accumulator variable total.

Based on the above ideas, we can write the following reduce function:

Array.prototype.myReduce = function(callback, initialValue) {
  let total = initialValue ? initialValue : this[0]; // 如果有初始值,使用初始值,否则使用数组的第一个元素
  for (let i = initialValue ? 0 : 1; i < this.length; i++) { // 如果有初始值,从0开始遍历,否则从1开始遍历
    total = callback(total, this[i], i, this); // 调用回调函数更新累加器变量的值
  }
  return total; // 返回累加器变量
}
Copy after login

3. Use of reduce function

Now that we have implemented the reduce function, then we should How to use it? Next, we will demonstrate the common usage of the reduce function.

  1. Calculate the sum of array elements

We can calculate the sum of array elements through the reduce function. As shown below:

const arr = [1, 2, 3, 4, 5];
const sum = arr.myReduce((total, currentValue) => total + currentValue); // 15
Copy after login
  1. Calculate the product of array elements

We can also calculate the product of array elements through the reduce function. As shown below:

const arr = [1, 2, 3, 4, 5];
const product = arr.myReduce((total, currentValue) => total * currentValue); // 120
Copy after login
  1. Calculate the average of array elements

We can also calculate the average of array elements through the reduce function. As shown below:

const arr = [1, 2, 3, 4, 5];
const avg = arr.myReduce((total, currentValue, i, arr) => {
  total += currentValue;
  if (i === arr.length - 1) {
    return total / arr.length;
  } else {
    return total;
  }
}); // 3
Copy after login

4. Summary

At this point, we have implemented the reduce function in Javascript. The reduce function is a very important function that can greatly simplify our operations on arrays. As long as we remember the principle of the reduce function, we can easily implement our own reduce function and use it to speed up the speed of writing code. Of course, for complex array processing scenarios, the reduce function may need further expansion and improvement.

The above is the detailed content of Detailed explanation of the principle and usage of javascript reduce function. For more information, please follow other related articles on the PHP Chinese website!

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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!