Home > Article > Web Front-end > Problem solving with recursive functions in JavaScript
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:
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!