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:
1 2 3 4 5 |
|
Then define another variable to point to this function, and then set the function to null
1 2 3 |
|
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
1 2 3 4 5 |
|
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:
1 2 3 4 5 |
|
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!