Home > Article > Web Front-end > Recursively call function method
Recursive: Call yourself again inside a function;
Efficiency: This call has not yet ended , the next call will start, and this call will be suspended until all calls are completed before returning in sequence.
It is shaped like a mathematical function: the factorial of f(n)
##ex: 5!=5*4! (5* 4*3*2*1)
4!=4*3! (4*3*2*1)
3!=3*2! (3*2*1)
2!=2*1! ( 2*1)
##1!=1;
F(n)! =n*f(n-1)!
<script>
//计算数字n的阶乘 (if方法)
function f(n){
if(n==1){ //边界条件
return 1;
}else{ //没到边界条件
return n*f(n-1);
}
}
/*或者:return n==1 ? 1 : n*f(n-1); (三目运算方法)
function f(n){
var result = return n==1 ? 1 : n*f(n-1);
return result;
}
*/
//计算5的阶乘?
function testF(){
var result = f(5);
console.log(result);
}
testF();
</script>
Exercise:
The following sequence: Fibonacci sequence
1,1,2,3,5,8,13 ,21,34,55………….
Known: The first number and the second number in the sequence are both 1
From the third Starting with numbers, each number is the sum of the previous two numbers
##
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <link rel="stylesheet" style="text/css" href=""> <style> </style> </head> <body> <script> function f(n){ if(n==1 || n==2){ return 1; }else{ return f(n-1)+f(n-2); } } function testF(){ var result=f(20); console.log(result); } testF(); </script> </body> </html>
The above is the detailed content of Recursively call function method. For more information, please follow other related articles on the PHP Chinese website!