Recursive function

1. Low-level: Call yourself

2. Recursive three steps {①. First find the stop condition (generally the first item at the beginning) ②. Find the relationship between each result and the previous line ③.

3.eg +=

//1. The height is 100 meters, and the height is half of the original height at the time of each fall, and the height at the time of the seventh bounce, using recursive implementation // Find the relation: the first time, 50, the second time, 25, the third time, 12.5···· // Deduce: Function fu(n){if(n===0)return 100; Return 0.5*fu(n-1); // relationship} var res =fu(7) console.log(res); / / results as follows: 0.78125 / / 2. The Fibonacci,1,2,3,5,8,13 · · · · · · / / 1 / / stop condition: n1 = 1, n2 = 1 / / looking for relationship: 1 + 1 = 2, 1 + 2 = 3, 2, 3 + 3 = 5 + 5 = 8... / / can be concluded that: Every result is equal to the sum of the first two f (n - 1) + f (n - 2) function fu (n) {if (n = = = 1 | | n = = = 2) {/ / stop conditions return 1; } return f(n-1)+f(n-2); } var res =fu(7) console.log(res); // Result: 13 //3. Factorial //5! = 1 * 2 * 3 * 4 * 5 / / 4! = 1 * 2 * 3 * 4 / / 3! = 1 * 2 * 3 / / 2. / / 1 = 1 * 2! Function fu(n){if (n === 1) {return 1; } return n * fu(n-1) } var res = fu(5) console.log(res); // The result is 120Copy the code

There are a lot of recursive methods, the above is just my personal understanding, if it is not good to find the end condition, then define a, for reference only, if there is a mistake thank you for correcting!