The use of recursive deep copy (one of the common interview questions)

Shallow vs. deep copy of the differences:

Shallow copy:  Only after all the data referenced down, still point to the same data modification after a storage address, copy, will also affect the original data in the object data

Deep copy:  all data copied down, after copying the data to be modified without affecting the original data

 

Realization of ideas:

  1. The data to be copied obj passed as a parameter reference
  2. Declare a variable to store the content of our copy out
  3. Determining whether obj is a reference type data, if not, it can be directly assigned (obj instanceof Type can be used to judge),
  4. As the use instanceof to determine whether the array is the object of the time, the return value is true, so when we judge, to determine whether obj is directly Array can avoid this problem
  5. Depending on the type of judgment, before imparting to give different types of variables: []: {}
  6. Obj in each cycle, if there is also complex data types, the direct use of recursive calls to copy function again
  7. Finally, this variable out to return

Code:

var obj = {    // original data, comprising strings, objects, functions, such as different types of array 
       name: " Test " ,
       main:{
           a:1,
           b:2
       },
       fn:function(){
           
       },
        friends:[1,2,3,[22,33]]
   }

   function copy(obj){
        the newobj the let = null ;    // content variable for storing a copy of the statement after
        
     // determine whether the data type is a complex type, if the call itself, the cycle again, if not, you can direct assignment,
      // because the cycle but can not be null type is object, so this needs to be judged null 
        IF ( typeof (obj) == ' Object ' && obj! == null ) {
        
    // declare a variable value for storing copy out, to store specific data types depending on the type of parameter declared 
            the newobj the instanceof the Array obj =? []: {};   
            
    // Each cycle of obj, if there is also a complex data type, then the recursive call directly copy function again 
            for ( var I in obj) {  
                newobj[i] = copy(obj[i])
            }
        }else{
            newobj = obj
        }    
      return the newobj;     // function must have a return value, otherwise the structure is undefined 
   }

    var obj2 = copy(obj)
    obj2.name = ' modified successfully ' 
    obj2.main.a = 100
   console.log(obj,obj2)

 

Guess you like

Origin www.cnblogs.com/likecn/p/11880161.html