This article analyzes the JavaScript recursive operation. Share to everyone for your reference, specific as follows:
Problem
A simple recursion that asks for the factorial of N:
function factorial (n) {
if (n<=1)
{return
1;
} else{return
factorial (n-1) *n;
}
If you use it as follows, you will get an error:
var fcopy = factorial;
factorial = null;
Alert (Fcopy (3));
Because the fcopy point to the function entity called factorial, factorial has been freed.
Way to solve
Using Arguments.callee
When the stream enters the function, it creates the runtime environment (scope chain, etc.) of the function, including arguments, where the arguments object has a property pointing to the function itself: Arguments.callee.
function factorial (n) {
if (n<=1)
{return
1;
} else{return
Arguments.callee (n-1) *n;
}
However, callee is not available in strict mode.
Using function expressions
var factorial = (function f (n) {
if (n<=1)
{return
1;
} else{return
F (n-1) *n
}
)
This is not what new technology is used, but in the original concept of an application, in the definition of factorial, directly create a function, and then the function of the reference to assign value to factorial.
More readers interested in JavaScript-related content can view this site: "JavaScript traversal algorithm and tips summary", "javascript array operation skills Summary", "JavaScript Mathematical calculation Usage Summary", " JavaScript data structure and algorithm skills summary, "JavaScript switching effects and techniques summary", "JavaScript Search Algorithm Skills Summary", "JavaScript animation effects and techniques summary" and "JavaScript error and debugging skills Summary"
I hope this article will help you with JavaScript programming.