JavaScript recursion detailed

JavaScript recursion detailed

1. What is recursion?

If a function can call itself internally, then this function is recursive. Simple understanding: a function calls itself internally, and this function is a recursive function.

As shown below:

function fn(){
 fn();
}
fn();

This function is a recursive function. When we print it directly, it will:

I found a printing error. Why? Because recursive functions have the same effect as loops. When there is no return value given to him, it will continue in an endless loop. So, we know:

Since recursion is prone to stack stack overflow errors, an exit condition return must be added.

How to write a correct recursive function? Take the above code as an example: for example, if we want to print 'hello' five times, we should write it like this:

var num = 1;
function fn(){
            console.log('Hello');
            if(num == 5){
                return;
            }
            num++;
            fn();
        }
        fn();

The print result is:

Now that we know what recursion is, let’s take a look at how to use recursion to solve problems!

2. Solve math problems using recursion

1. Find the factorial of 1 * 2 * 3 * 4 …*n

The code is as follows:

 function fn(n){
           if(n == 1){
               return 1;
           }
           return n*fn(n-1);
       }
       console.log('The factorial of 1-20 is: '+fn(20));
       console.log('The factorial of 1-10 is: '+fn(10));
       console.log('The factorial of 1-5 is: '+fn(5));

The print result is:

2. Find the Fibonacci sequence

The Fibonacci sequence, also known as the "rabbit sequence", refers to a sequence of numbers :、1、1、2、3、5、8、13、21、34、……, that is, the value of the third term is the sum of the previous two terms. The user inputs an n and gets the number at that position.

The code is as follows:

function fb(n){
            if(n === 1 || n === 2){
                return 1;
            }
            return fb(n-1) + fb(n-2);
        }
       console.log('The value of the third Fibonacci number is: '+fb(3));
       console.log('The value of the 10th Fibonacci number is: '+fb(10));

The print result is:

3. Use recursion to find the corresponding data object

Return the corresponding data object according to id

There are objects like this:

        var date = [{
            id:1,
            name:'Electrical appliances',
            goods:[{
                id: 11,
                gname:'mobile phone'
            },{
                id: 12,
                gname: 'Computer'
            }]
        },{
            id:2,
            name:'clothing',
            goods:[{
                id : 21,
                gname:'pants'
            },{
                id : 22,
                gname : 'coat'
                }]
        },{
            id : 3,
            name: 'Food'
                }];

Now we need to return the corresponding data object by inputting id .

First, we can use for...Each() to traverse the array and get each value, as shown below:

function getId(array,id){
                    array.forEach(function(value){
                        console.log(value);
                    })
                }
                getId(date,1);

The printed result is:

At this time, if we want to get the value of the object with id 1, we can do this:

function getId(array,id){
                    array.forEach(function(value){
                       if(value.id === id){
                           console.log(value);
                       }
                    })
                }
                getId(date,1);

The print result is:

Yes, but what if we want to get the value of the object with id 11? Obviously, calling the function directly is not feasible, because we only get the value of the outermost object through for...Each, but the specific classification of the inner layer is not obtained. At this time, we can get the value of the inner object by recursively calling the getId(array,id) function.

The operation is as follows:

 function getId(array,id){
                    array.forEach(function(value){
                       if(value.id === id){
                           console.log(value);
                       }else if(value.goods && value.goods.length != 0){
                            getId(value.goods,id);
                       }

                    })
                }
                // getId(date,1);
                getId(date,11);

The printed result is:

This is the end of this article about JavaScript recursion. For more relevant JavaScript recursion content, please search 123WORDPRESS.COM’s previous articles or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Detailed analysis of classic JavaScript recursion case questions
  • JavaScript recursive function definition and usage example analysis
  • JavaScript recursive function definition and usage example analysis
  • A brief analysis of JavaScript recursive operation examples

<<:  KVM virtualization installation, deployment and management tutorial

>>:  A simple way to call desktop exe programs on a web page

Recommend

How to represent various MOUSE shapes

<a href="http://" style="cursor...

How to use VLAN tagged Ethernet card in CentOS/RHEL system

In some scenarios, we want to assign multiple IPs...

Detailed code examples of seven methods for vertical centering with CSS

When we edit a layout, we usually use horizontal ...

WeChat applet custom tabBar step record

Table of contents 1. Introduction 2. Customize ta...

Mybatis implements SQL query interception and modification details

Preface One of the functions of an interceptor is...

How to set the page you are viewing to not allow Baidu to save its snapshot

Today, when I searched for a page on Baidu, becaus...

Docker installation and configuration command code examples

Docker installation Install dependency packages s...

Detailed explanation of how to view MySQL memory usage

Preface This article mainly introduces the releva...

Teach you how to quickly enable self-monitoring of Apache SkyWalking

1. Enable Prometheus telemetry data By default, t...

Implementation of HTML command line interface

HTML Part Copy code The code is as follows: <!D...

How to use squid to build a proxy server for http and https

When we introduced nginx, we also used nginx to s...

A brief understanding of the three uses of standard SQL update statements

1. Environment: MySQL-5.0.41-win32 Windows XP Pro...

HTML framework_Powernode Java Academy

1. Framework A browser document window can only d...

The front-end must know how to lazy load images (three methods)

Table of contents 1. What is lazy loading? 2. Imp...