Deep copy of principle

 

1. The first type judgment performed 

 if(obj==null)   return obj;
   if(obj  instanceof RegExp)    return  new  RegExp(obj);
   if(obj instanceof Date)       return  new  Date(obj);
   //...
   if(typeof obj !== 'object')    return  obj;

2. The judge is an array or an object 

 let  instance  = new  obj.constructor;

demo 

function deepClone(obj,hash=new WeakMap()) {
   if(obj==null)   return obj;
   if(obj  instanceof RegExp)    return  new  RegExp(obj);
   if(obj instanceof Date)       return  new  Date(obj);
   //...
   if(typeof obj !== 'object')    return  obj;

   let  instance  = new  obj.constructor;

//    if(hash.has(obj))   return hash.get(obj);
//    hash.set(obj,instance);
//    for (const key in obj) {
//        if (obj.hasOwnProperty(key)) {
//            instance[key] =deepClone(obj[key],hash);
//        }
//    }
   return  instance;
  }
console.log(deepClone({a:1,b:2,c:{c:1}}));
console.log(deepClone([1,2,3,4]));

Output:

{}
[]
 
3. traverse an array or array use for ..... in  
 
4. Copy
   for (const key in obj) {
       if (obj.hasOwnProperty(key)) {
           instance[key] =deepClone(obj[key],hash);
       }
   }

5.  

 if(hash.has(obj))   return hash.get(obj);
   hash.set(obj,instance);

Here is to determine whether there was a copy of a copy of the return if it

The mapping 

 
 
Complete demo:
 
function deepClone(obj,hash=new WeakMap()) {
   if(obj==null)   return obj;
   if(obj  instanceof RegExp)    return  new  RegExp(obj);
   if(obj instanceof Date)       return  new  Date(obj);
   //...
   if(typeof obj !== 'object')    return  obj;

   let  instance  = new  obj.constructor;

   if(hash.has(obj))   return hash.get(obj);
   hash.set(obj,instance);
   for (const key in obj) {
       if (obj.hasOwnProperty(key)) {
           instance[key] =deepClone(obj[key],hash);
       }
   }
   return  instance;
  }
console.log(deepClone({a:1,b:2,c:{c:1}}));
console.log(deepClone([1,2,3,4]));

Output:

 

{ a: 1, b: 2, c: { c: 1 } }
[ 1, 2, 3, 4 ]

 

Guess you like

Origin www.cnblogs.com/guangzhou11/p/11328261.html