JavaScript Recursive
1. Recursive definition
A recursive function is formed when a function calls itself by name, as follows:
1 function factorial (num) {2 if (Num<=1) {3 } 5 else{6 return num * Factorial (num-1 }8}
The above function indicates that there is no problem, but the following code causes it to go wrong:
1 var anotherfactorial = factorial2 factorial = Null3 console.log (anotherfactorial (4)) //Error
cause of error:factorial variable after performing the above operation is empty, the result points to the original function of the reference is only one left, but in the next call Anotherfactorial must execute factorial, and factorial is no longer a function , so it leads to errors, and in this case using Aruguments.callee can solve the problem
Aruguments.callee: is a pointer to a function, so it can be used to implement a recursive call to a function
1 function factorial (num) {2 if (num <= 1) {3 } 5 else{6 return num* Arguments.callee (num-1} 9 10//You can also use a named function expression to achieve the same effect as above, var factorial = (function f (num) {if (num <= 1
}15 else
{num*f (num-1 }18})
2. Classic recursion
Altogether 10 stairs, each can walk one step or two steps, beg altogether how many kind of walk method, the idea:
To go to N (n=10) level, can be divided into 2 kinds of situations.
- Two steps from the n-2 level
- One step from the n-1 level
Then the situation of n-2 and n-1 is divided into two categories, and so on.
Then the sum of the way is the n-2 and the n-1 of the way of the law.
So the recursion to the most basic (the current person on the No. 0 order stair)
No. 0 Step Step: 0
1th Step Step: 1
2nd Step: 2 (+ + or 2)
Get the formula, which is the Fibonacci sequence.
1 var fib = function (n) {2 if (n = = 1) {3 return 1 } 5 else if (n==2) {6 return 2 } 8 else if (n>2) {9 return fib (n-1) + fib (n-2}12 console.log (fib));
Recursion in JavaScript