Home  >  Article  >  Web Front-end  >  Problem solving with recursive functions in JavaScript

Problem solving with recursive functions in JavaScript

黄舟
黄舟Original
2017-11-18 11:28:481401browse

In the previous article, we introduced to you the use of recursive functions in JavaScript, then when we use the recursive functions in JavaScript , there will be some problems. Today I will give you an example to introduce the problem of recursive functions in JavaScript!

First define a recursive function to find the factorial of a positive integer N:

function factorial(num){
    if(num<=1)
        return 1;
    return num*factorial(num-1);
}

Then define another variable to point to this function, and then set the function to null

var anotherFactorial=factorial;
factorial=null;
alert(anotherFactorial(4));//报错

Why Will an error be reported? Because inside the function factorial, factorial itself is called recursively, and the above code sets factorial to null, so it is no longer a function. This may sound a bit strange, but this is how JavaScript handles it internally. How to solve this problem? One way is to replace the function itself with arguments.callee inside the function

function factorial(num){    
if(num<=1)        
return 1;    
return num * arguments.callee(num-1);
}

In this way, no matter which variable the function is assigned to, there will be no problem in subsequent calls. Therefore, it is recommended to use arguments.callee inside a recursive function instead of the function itself. Or you can use Function expression to solve this problem:

var factorial = (function f(num){    
if(num<=1)        
return 1;    
return num*f(num-1);
});

In this way, no matter whether the variable factorial variable is assigned to another variable, there will be no problem with the recursive call.

Summary:

Through the detailed introduction of this article, I believe that friends will have a new understanding of the problem of recursive functions in JavaScript. Hope it helps with your work!

Related recommendations:

Detailed explanation of the use of recursive functions in JavaScript


Analysis and explanation of recursive functions in JavaScript


Refined understanding of recursive functions in JavaScript and sharing of sample codes

The above is the detailed content of Problem solving with recursive functions in JavaScript. 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