当前位置:网站首页>That's why you can't understand recursion

That's why you can't understand recursion

2022-07-06 22:23:00 Eat by technology

Today, let's talk about recursion , Bloggers have stumbled here , Don't be like a blogger !!

One 、 What is recursion

Two 、 Use recursion to find 1~n The factorial

3、 ... and 、 Using recursion to find Fibonacci sequence

Four 、 Using recursion to traverse data

One 、 What is recursion

recursive : If a function can call itself internally , So this function is recursive . Simple understanding : The function itself calls itself , This function is a recursive function .

Be careful : Recursive functions work just as well as loops , Because recursion is easy to happen “ Stack overflow ” error (stack overflow), So you have to add exit conditions return.

Two 、 Use recursion to find 1~n The factorial

// Use recursive function to find 1~n The factorial  1 * 2 * 3 * 4 * ..n
 function fn(n) {
     if (n == 1) { // The end condition 
       return 1;
     }
     return n * fn(n - 1);
 }
 console.log(fn(3));

The result of the above code is :

3、 ... and 、 Using recursion to find Fibonacci sequence

//  Using recursive function to find Fibonacci sequence ( Rabbit sequence )  1、1、2、3、5、8、13、21...
//  The user enters a number  n  We can work out   This number corresponds to the rabbit sequence value 
//  We just need to know what the user entered n  The first two items (n-1 n-2) You can figure it out n  Corresponding sequence value 
function fb(n) {
  if (n === 1 || n === 2) {
        return 1;
  }
  return fb(n - 1) + fb(n - 2);
}
console.log(fb(6));

The result of the above code is :

Four 、 Using recursion to traverse data

//  We want to make input id Number , Data objects that can be returned 
 var data = [{
   id: 1,
   name: ' Home appliance ',
   goods: [{
     id: 11,
     gname: ' The refrigerator ',
     goods: [{
       id: 111,
       gname: ' haier '
     }, {
       id: 112,
       gname: ' beauty '
     },

            ]

   }, {
     id: 12,
     gname: ' Washing machine '
   }]
 }, {
   id: 2,
   name: ' dress '
}];
//1. utilize  forEach  Go through every object inside 
 function getID(json, id) {
   var o = {};
   json.forEach(function(item) {
     // console.log(item); // 2 Array elements 
     if (item.id == id) {
       // console.log(item);
       o = item;
       return o;
       // 2.  We want to get the data from the inner layer  11 12  You can use recursive functions 
       //  There should be goods This array, and the length of the array is not  0 
     } else if (item.goods && item.goods.length > 0) {
       o = getID(item.goods, id);
     }
   });
   return o;
}
console.log(getID(data, 112));

The running result of the above code is :

原网站

版权声明
本文为[Eat by technology]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202131052513378.html