js中对象的浅拷贝与深拷贝,以及对象深拷贝的递归方法

浅拷贝与深拷贝

浅拷贝:只拷贝地址
深拷贝:将复合数据类型重新生成一份,进行拷贝


       //浅拷贝
        <script type="text/javascript">            
        var obj = {a:1,b:{age:18}};                       
         var obj2 = obj;//浅拷贝                       
         console.log(obj === obj2)                                  
         obj.a = 1000;           
          console.log(obj2) //{a: 1000,b: {age: 18}}           
          console.log(obj)//{a: 1000,b: {age: 18}}
         ```

        //深拷贝
        var obj = {a:1,b:{age:18}};            
        var obj3 = {};           
        for(var prop in obj){              
             //a                 
             //b
          console.log(prop)
          if(typeof obj[prop] =='object'){
                var tmp =  obj[prop];                 
                console.log(tmp)                                       
                var tmpObj = {};                    
                for(var p in tmp){ 
          	  tmpObj[p] = tmp[p]                    
            	}                    
                obj3[prop] = tmpObj; 
            }else{                    
             obj3[prop] = obj[prop]              
            }                           
       }
       obj.a = 200;  
       obj.b.age = 199 
       console.log(obj3) //{a: 1,b: {age: 18}}
       console.log(obj) //{a: 200,b: {age: 199}}

深拷贝的递归方法

   function deepCopy(obj){
     var o = {};                
     for(var prop in obj){                    
     if(typeof obj[prop] =='object'){                        
     //要拷贝的属性值是一个对象                        
     	var resObj = deepCopy(obj[prop]);                        
     	o[prop] = resObj;                    
     }else{                       
      	o[prop] = obj[prop]                    
      }                                    
    }               
      return o;                            
  }
发布了10 篇原创文章 · 获赞 12 · 访问量 509

猜你喜欢

转载自blog.csdn.net/Mine____/article/details/103913337