Recursive __javascript of JS function

Source: Internet
Author: User

This blog mainly tells about the function of JS recursive, mainly from the "variable + function" and "function + variable" Two aspects explained.
Relatively simple, directly on the code.

I. Knowledge Description

function Fun ()
{
    //self calls itself, called recursive call
    fun ();
    Console.log ("M2");
}
Fun ();

Second, function + variable

Use recursive return for 5 factorial
//n! = n * (n-1)!

Defines a function that is used to find the factorial function of n
func (n)
{
    if (n = 1)
    {return
        1;
    }

    Func (n-1) because the parameters passed are n-1, then the factorial return
    N * func (n-1) is asked (n-1);
Console.log (     func (5)   );

function + function

The question of Netherfield (Rabbit Polaci)--a pair of rabbits are born every month from the 3rd month after birth, rabbit long to the third month after a pair of rabbits each month, if the rabbit does not die, ask the number of rabbits per month
//yield analysis: 1, 1, 2, 3, 5, 8, 13, 21 ... The total number of rabbits per month = number of rabbits in the month of N-1 + the total number of rabbits in  n-2 months
//problem: Find the total number of rabbits in any month

function func (n)
{
    if ( n = = 0 | | n = = 1)
    {return
        1;
    }
    return func (n-1) + func (n-2);
}

var a = func ();
Console.log (a);

In a way, the recursion of a function is to call itself in a function . The concept is the case, it depends on how flexible you call.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.