Table of Contents
Little Lizi:
Recursion:
Little chestnuts:
Home Web Front-end JS Tutorial Detailed explanation of the usage of JS recursion

Detailed explanation of the usage of JS recursion

Jun 29, 2020 pm 05:46 PM
js recursion

Detailed explanation of the usage of JS recursion

recursion:

The function calls the function itself, which is recursion. Recursion must have an end condition

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

    function f1() {

        console.log("从前有座山,山里有个庙,庙里有个老和尚给小和尚讲故事:");

        f1();

    };

    f1();//浏览器崩溃,因为没有结束条件——死循环

 

    改进如下:

        var i=0;

    function f1() {

        i++;

        if (i<5){

            f1();

        }

        console.log("从前有座山,山里有个庙,庙里有个老和尚给小和尚讲故事:");

    };

    f1();

Copy after login

Related learning tutorial: javascript tutorial

Little Lizi:

Recursive implementation: find the sum of n numbers n=5 ------->5 4 3 2 1

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

<strong>//for 循环写法:

    var sum=0;

    for (var i=0;i<=5;i++){

        sum+=i;

    }

    console.log(sum);

----------------------分割线---------------------------

 

   function getSum(x) {

        if (x==1){

          return 1

        }

        return x+getSum(x-1);

    };

 

    var sum1=getSum(5);

    console.log(sum1);

    console.log(getSum(10));</strong>

Copy after login
Copy after login

Execution process:
The code executes getSum(5)—>Enter the function, x is 5 at this time, and 5 getSum(4) is executed. This When the code waits
At this time 5 getSum(4), the code does not calculate first, executes getSum(4) first, enters the function, executes 4 getSum(3), wait, executes getSum(3) first, Enter the function, execute 3 getSum(2), wait, execute getSum(2) first, enter the function, execute 2 getSum(1); wait, execute getSum(1) first, execute the judgment of x==1, return 1 ,So,
The result of getSum(1) at this time is 1, start to go out
2 getSum(1) The result at this time is: 2 1
Execution:
getSum(2) ---->2 1
3 getSum(2) The result at this time is 3 2 1
4 getSum(3) The result at this time is 4 3 2 1
5 getSum(4) This The result is 5 4 3 2 1

1

<strong>    结果:15</strong>

Copy after login
Copy after login

A few more:

1

2

3

4

5

6

7

8

9

10

<strong>    //递归案例:求一个数字各个位数上的数字的和:  123   --->6 ---1+2+3

    //523

    function getEverySum(x) {

        if(x<10){

            return x;

        }

        //获取的是这个数字的个位数

        return x%10+getEverySum(parseInt(x/10));

    }

    console.log(getEverySum(1364));//5</strong>

Copy after login

1

2

3

4

5

6

7

8

9

<strong> //递归案例:求斐波那契数列

 

    function getFib(x) {

        if(x==1||x==2){

            return 1

        }

        return getFib(x-1)+getFib(x-2);

    }

    console.log(getFib(12));</strong>

Copy after login

Recursion:

The function calls the function itself, which is recursion. The recursion must have an end condition

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

function f1() {

    console.log("从前有座山,山里有个庙,庙里有个老和尚给小和尚讲故事:");

    f1();

};

f1();//浏览器崩溃,因为没有结束条件——死循环

 

改进如下:

    var i=0;

function f1() {

    i++;

    if (i<5){

        f1();

    }

    console.log("从前有座山,山里有个庙,庙里有个老和尚给小和尚讲故事:");

};

f1();

Copy after login

Little chestnuts:

Recursive implementation: Find the sum of n numbers n=5 ------->5 4 3 2 1

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

<strong>//for 循环写法:

    var sum=0;

    for (var i=0;i<=5;i++){

        sum+=i;

    }

    console.log(sum);

----------------------分割线---------------------------

 

   function getSum(x) {

        if (x==1){

          return 1

        }

        return x+getSum(x-1);

    };

 

    var sum1=getSum(5);

    console.log(sum1);

    console.log(getSum(10));</strong>

Copy after login
Copy after login

Execution process:
The code executes getSum(5)—>Enter the function. At this time, x is 5, and 5 getSum(4) is executed. At this time, the code waits.
At this time, 5 getSum(4), the code Do not calculate first, execute getSum(4) first, enter the function, execute 4 getSum(3), wait, execute getSum(3) first, enter the function, execute 3 getSum(2), wait, execute getSum first (2), enter the function, execute 2 getSum(1); wait, execute getSum(1) first, execute the judgment of x==1, return 1, so,
The result of getSum(1) at this time is 1. Start walking out
2 getSum(1) The result at this time is: 2 1
Execution:
getSum(2)---->2 1
3 getSum(2 ) The result at this time is 3 2 1
4 getSum(3) The result at this time is 4 3 2 1
5 getSum(4) The result at this time is 5 4 3 2 1

1

<strong>    结果:15</strong>

Copy after login
Copy after login

A few more:

1

2

3

4

5

6

7

8

9

10

<strong>    //递归案例:求一个数字各个位数上的数字的和:  123   --->6 ---1+2+3

    //523

    function getEverySum(x) {

        if(x<10){

            return x;

        }

        //获取的是这个数字的个位数

        return x%10+getEverySum(parseInt(x/10));

    }

    console.log(getEverySum(1364));//5</strong>

Copy after login
rrree

The above is the detailed content of Detailed explanation of the usage of JS recursion. For more information, please follow other related articles on the PHP Chinese website!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Recursive implementation of C++ functions: Is there a limit to recursion depth? Recursive implementation of C++ functions: Is there a limit to recursion depth? Apr 23, 2024 am 09:30 AM

The recursion depth of C++ functions is limited, and exceeding this limit will result in a stack overflow error. The limit value varies between systems and compilers, but is usually between 1,000 and 10,000. Solutions include: 1. Tail recursion optimization; 2. Tail call; 3. Iterative implementation.

Do C++ lambda expressions support recursion? Do C++ lambda expressions support recursion? Apr 17, 2024 pm 09:06 PM

Yes, C++ Lambda expressions can support recursion by using std::function: Use std::function to capture a reference to a Lambda expression. With a captured reference, a Lambda expression can call itself recursively.

Recommended: Excellent JS open source face detection and recognition project Recommended: Excellent JS open source face detection and recognition project Apr 03, 2024 am 11:55 AM

Face detection and recognition technology is already a relatively mature and widely used technology. Currently, the most widely used Internet application language is JS. Implementing face detection and recognition on the Web front-end has advantages and disadvantages compared to back-end face recognition. Advantages include reducing network interaction and real-time recognition, which greatly shortens user waiting time and improves user experience; disadvantages include: being limited by model size, the accuracy is also limited. How to use js to implement face detection on the web? In order to implement face recognition on the Web, you need to be familiar with related programming languages ​​and technologies, such as JavaScript, HTML, CSS, WebRTC, etc. At the same time, you also need to master relevant computer vision and artificial intelligence technologies. It is worth noting that due to the design of the Web side

How to create a stock candlestick chart using PHP and JS How to create a stock candlestick chart using PHP and JS Dec 17, 2023 am 08:08 AM

How to use PHP and JS to create a stock candle chart. A stock candle chart is a common technical analysis graphic in the stock market. It helps investors understand stocks more intuitively by drawing data such as the opening price, closing price, highest price and lowest price of the stock. price fluctuations. This article will teach you how to create stock candle charts using PHP and JS, with specific code examples. 1. Preparation Before starting, we need to prepare the following environment: 1. A server running PHP 2. A browser that supports HTML5 and Canvas 3

Essential tools for stock analysis: Learn the steps to draw candle charts with PHP and JS Essential tools for stock analysis: Learn the steps to draw candle charts with PHP and JS Dec 17, 2023 pm 06:55 PM

Essential tools for stock analysis: Learn the steps to draw candle charts in PHP and JS. Specific code examples are required. With the rapid development of the Internet and technology, stock trading has become one of the important ways for many investors. Stock analysis is an important part of investor decision-making, and candle charts are widely used in technical analysis. Learning how to draw candle charts using PHP and JS will provide investors with more intuitive information to help them make better decisions. A candlestick chart is a technical chart that displays stock prices in the form of candlesticks. It shows the stock price

Recursive implementation of C++ functions: Comparative analysis of recursive and non-recursive algorithms? Recursive implementation of C++ functions: Comparative analysis of recursive and non-recursive algorithms? Apr 22, 2024 pm 03:18 PM

The recursive algorithm solves structured problems through function self-calling. The advantage is that it is simple and easy to understand, but the disadvantage is that it is less efficient and may cause stack overflow. The non-recursive algorithm avoids recursion by explicitly managing the stack data structure. The advantage is that it is more efficient and avoids the stack. Overflow, the disadvantage is that the code may be more complex. The choice of recursive or non-recursive depends on the problem and the specific constraints of the implementation.

PHP and JS Development Tips: Master the Method of Drawing Stock Candle Charts PHP and JS Development Tips: Master the Method of Drawing Stock Candle Charts Dec 18, 2023 pm 03:39 PM

With the rapid development of Internet finance, stock investment has become the choice of more and more people. In stock trading, candle charts are a commonly used technical analysis method. It can show the changing trend of stock prices and help investors make more accurate decisions. This article will introduce the development skills of PHP and JS, lead readers to understand how to draw stock candle charts, and provide specific code examples. 1. Understanding Stock Candle Charts Before introducing how to draw stock candle charts, we first need to understand what a candle chart is. Candlestick charts were developed by the Japanese

Detailed explanation of C++ function recursion: application of recursion in string processing Detailed explanation of C++ function recursion: application of recursion in string processing Apr 30, 2024 am 10:30 AM

A recursive function is a technique that calls itself repeatedly to solve a problem in string processing. It requires a termination condition to prevent infinite recursion. Recursion is widely used in operations such as string reversal and palindrome checking.

See all articles