How to Deep clone in javascript

前端 未结 19 1536
-上瘾入骨i
-上瘾入骨i 2020-11-22 02:06

How do you deep clone a JavaScript object?

I know there are various functions based on frameworks like JSON.parse(JSON.stringify(o)) and $.extend(t

19条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-22 02:52

    This one, using circular reference, works for me

     //a test-object with circular reference :
     var n1 = {   id:0,   text:"aaaaa",   parent:undefined} 
     var n2 = {  id:1,   text:"zzzzz",   parent:undefined } 
     var o = { arr:[n1,n2],   parent:undefined } 
     n1.parent = n2.parent = o;
     var obj = {   a:1,   b:2,   o:o }
     o.parent = obj;
    
     function deepClone(o,output){ 
    
         if(!output) output = {};  
         if(o.______clone) return o.______clone;
         o.______clone = output.______clone = output;
    
       for(var z in o){
    
         var obj = o[z];
         if(typeof(obj) == "object") output[z] = deepClone(obj)
         else output[z] = obj; 
        }
    
       return output;
    }
    
    console.log(deepClone(obj));
    

提交回复
热议问题