Recursive function in JavaScript
What is recursion?
This function is invoked in the body of the function. It is a call mode, a logic-based expression.
== Recursion consume large amounts of memory, rarely used in the actual development ==
Note: Recursive most important is the termination condition.
Recursive calculation of the factorial of n
function acc(n){
if(n<=1){
return 1;
}else{
return n*acc(n-1)
}
}
console.log(acc(4));
Calculated here are 4 factorial; from the beginning, return 1; and 2, return 2 by acc (1) - 1 is multiplied by 2; ... sequentially
The use of recursion Fibonacci number (1,1,2,3,5,8,13,21,34,55,89 ...)
var m=1;
while(true){
function fiber(m){
if(m-1==0 || m-2==0){
return 1;
}else{
return (fiber(m-1)+fiber(m-2));
}
}
console.log(fiber(m));
m++;
}
The characteristics of the Fibonacci columns, m represents the number of columns of items, we can get the fiber (m) = fiber (m -2) + fiber (m-1);
it requires: m> 2; so I use to if () {} else {} a branched structure.
When m = 1, m = 2, return 1;
utilized herein made of a while loop, a digital output in sequence for each item.
We do not understand can be calculated from recursive 1 + 2 + 3 + 4 + 5 =? Start;
function fn(n){
if(n<=1){
return 1;
}else{
return n+fn(n-1)
}
}
console.log(fn(5))
Where n represents both the first several, and they represent a corresponding entry in the digital
value of the return current item n with the former one.