About recursion.

1. What is recursion?

  The so-called recursive call is their own, take the form of a function call function own work.

  javascript recursion most typical application is factorial and Porfirio Fibonacci sequence.

2. For chestnut: Find the 1 + 2 + 3 ... + n and?

  • A method for using the loop calculated:
function sum(n) {
     var total = 0
     for (var i = 1; i <= n; i++) {
          total = total + i
      }
        return total
}
 console.log(sum(3)); //得出6
  • Method recursive requirements:
function SUM1 (n-) {
   IF (=== n-1 ) {// when n = 1, the termination condition is given to
      return 1 ; 
   } 
   return SUM1 (n-- 1) + n-; 
} 
 the console.log (SUM1 ( . 3 )); // 6
        

  When recursive, improper handling will be caught in an endless loop.

3. The use of recursion results Porfirio Fibonacci number sequence.

  What is Porphyria Fibonacci series, Fibonacci number column, also known as the golden cut the number of columns, referring to Fibonacci series columns from the beginning of paragraph 3, each of which is equal to the sum of the first two. Such as: (1,1,2,3,5,8,13,21). 

function FB (n-) {
     IF (n-n-||. 1 == == 2 ) {// start from the third
         return . 1 
    } 
        
    return FB (n--. 1) FB + (2-n- ) 
 } 
the console.log (FB (4 )) // 3

4. The use of recursive deep copy.

  var objCopy = function (obj) {
      if (typeof obj !== 'object') return;
       // // The type judgment obj is an array of new objects or
      var newObj = obj instanceof Array ? [] : {};
        for (var key in obj) {
           if (obj.hasOwnProperty(key)) {
              newObj[key] = typeof obj[key] === 'object' ? objCopy(obj[key]) : obj[key];
            }
        }
        return newObj;
    }
    was sourObj = {
       a: 1,
       name: 'hello',
       b: 23
     }
     let targeObj = objCopy(sourObj, {});
     targeObj.a = 10;
     console.log(sourObj);  // {a: 1, name: "hello", b: 23}
     console.log(targeObj);  // {a: 10, name: "hello", b: 23}

 

Knot: write a recursive most important is to find the company and termination conditions recursion, or very easy to fall into an infinite loop, the seemingly simple, but there are many drawbacks recursion, use caution.

  

Guess you like

Origin www.cnblogs.com/0314dxj/p/11542222.html