1. What is recursion

Recursion: A function is recursive if it can call itself internally. Simple to understand: a function that calls itself internally is a recursive function

Note: Recursive functions function as loops, recursion is prone to “stack overflow” error, so you must add an exit condition return.

2. Use recursion to find the factorial of 1~n

1 * 2 * 3 * 4 *... N function fn(n) {if (n == 1) {return 1; } return n * fn(n - 1); } console.log(fn(3));Copy the code

3. Using recursion to find Fibonacci sequence

// Fibonacci sequence 1, 1, 2, 3, 5, 8, 13, 21... / / the user to enter a number n can work out the number sequence of rabbit corresponding value / / we only need to know that the first two of user input n (n - 1 n - 2) n corresponding sequence value function can be calculated fb (n) {if (n = = = 1 | | n = = = 2) { return 1; } return fb(n - 1) + fb(n - 2); } console.log(fb(3));Copy the code

4. Use recursion to iterate over data

Var data = [{id: 1, name: 'goods ', goods: [{id: 11, gname:' refrigerator ', goods: [{id: 111, gname: 'refrigerator ', goods: [{id: 111, gname:' goods'] "Haier"}, {id: 112, gname: 'beauty'},]}, {id: 12, gname: 'washing machine'}]}, {id: 2, name: 'clothing'}]; Function getID(json, id) {var o = {}; function getID(json, id) {var o = {}; json.forEach(function(item) { // console.log(item); If (item.id == id) {// console.log(item); o = item; return o; } else if (item.goods && item.goods. Length > 0) {o = (item.goods && item.goods getID(item.goods, id); }}); return o; }Copy the code