Home > Article > Web Front-end > How JavaScript uses recursion
This article will introduce you to the JavaScript recursive method. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.
The function calls the function itself. This is recursion. Recursion must have an end condition
function f1() { console.log("从前有座山,山里有个庙,庙里有个老和尚给小和尚讲故事:"); f1(); }; f1();//浏览器崩溃,因为没有结束条件——死循环 改进如下: var i=0; function f1() { i++; if (i<5){ f1(); } console.log("从前有座山,山里有个庙,庙里有个老和尚给小和尚讲故事:"); }; f1();
Recursive implementation: Find the sum of n numbers n=5 ------->5 4 3 2 1
//for 循环写法: var sum=0; for (var i=0;i<=5;i++){ sum+=i; } console.log(sum); ----------------------分割线--------------------------- function getSum(x) { if (x==1){ return 1 } return x+getSum(x-1); }; var sum1=getSum(5); console.log(sum1); console.log(getSum(10));
Execution process:
The code executes getSum(5)—>Enter the function, x is 5 at this time, and 5 getSum(4) is executed. At this time The code waits for
At this time, 5 getSum(4), the code does not perform calculations first, executes getSum(4) first, enters the function, and executes 4 getSum(3), waits, and executes getSum(3 first) ), enter the function, execute 3 getSum(2), wait, execute getSum(2) first, enter the function, execute 2 getSum(1); wait, execute getSum(1) first, and execute the judgment of x==1, return 1, so,
The result of getSum(1) at this time is 1, start to go out
2 The result of getSum(1) at this time is: 2 1
Execution:
getSum(2)---->2 1
3 getSum(2) The result at this time is 3 2 1
4 getSum( 3) The result at this time is 4 3 2 1
5 getSum(4) The result at this time is 5 4 3 2 1
结果:15
A few more:
//递归案例:求一个数字各个位数上的数字的和: 123 --->6 ---1+2+3 //523 function getEverySum(x) { if(x<10){ return x; } //获取的是这个数字的个位数 return x%10+getEverySum(parseInt(x/10)); } console.log(getEverySum(1364));//5
//递归案例:求斐波那契数列 function getFib(x) { if(x==1||x==2){ return 1 } return getFib(x-1)+getFib(x-2); } console.log(getFib(12));
[Recommended learning: javascript advanced tutorial]
The above is the detailed content of How JavaScript uses recursion. For more information, please follow other related articles on the PHP Chinese website!