Home  >  Article  >  Web Front-end  >  Analysis of js recursion principle

Analysis of js recursion principle

小云云
小云云Original
2018-03-22 16:09:442078browse

This article mainly tells you about the function recursion of JS, mainly from the two aspects of "variable + function" and "function + variable". I hope it can help you.

Relatively simple, just enter the code directly.

1. Knowledge description

function fun()
{    // 自己调用自己,称为递归调用
    fun();
    console.log("m2");
}fun();

2. Function + variable

// 用递归 来求 5 的阶乘// n! = n * (n-1)!// 定义一个函数,用于求 n 的阶乘function func(n){
    if (n == 1)
    {        return 1;
    }    // func(n-1) 因为传递的参数是 n-1,那么就是求 (n-1) 的阶乘
    return n * func(n-1);
}
console.log(     func(5)   );

3. Function + function

//斐波拉契题(兔子生兔子题目)--从出生后第3个月起每个月都生一对兔子,小兔子长到第三个月后每个月又生一对兔子,假如兔子都不死,问每个月的兔子对数为多少// 产量分析:1, 1, 2, 3, 5, 8, 13, 21 。。。// 第n个月的兔子总数  =  第n-1个月的兔子总数 + 第n-2个月的兔子总数// 问题: 求任意月兔子的总数function func( n )
{    if (n == 0 || n == 1)
    {        return 1;
    }    return func(n-1) + func(n-2);
}var a = func(22);
console.log(a);

To put it bluntly, the recursion of a function is to call itself in the function. The concept is like this, it just depends on how you use it flexibly.

Related recommendations:

js tail recursion optimization code sharing

jQuery realizes the recursive infinite layer function

Detailed explanation of php recursive function

The above is the detailed content of Analysis of js recursion principle. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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