zoukankan      html  css  js  c++  java
  • JS | 数组的深拷贝与浅拷贝

    浅拷贝与深拷贝的区别

    浅拷贝只复制指向某个对象的指针,而不复制对象本身,新旧对象还是共享同一块内存(操作新旧对象时会相互影响)。但深拷贝会另外创造一个一模一样的对象,新对象跟原对象不共享内存,修改新对象不会改到原对象。
    下面总结浅拷贝和深拷贝的几种方式:

    浅拷贝

    Object.assign

    var obj = { a: {a: "hello world", b: 31},b:34 }; 
    var cloneObj = Object.assign(obj); 
    cloneObj.a.a = "change world"; 
    cloneObj.b = 68; 
    cloneObj.a.b = 35; 
    console.log(obj); 
    //=> {a: {a: "change world", b: 31}b: 68} 
    console.log(cloneObj); 
    //=> {a: {a: "change world", b: 31}b: 68} 
    console.log(obj.a === cloneObj.a); 
    //=>true
    

    lodash的 _.clone

    var obj = { a: {a: "hello world", b: 31},b:34 };
    var cloneObj = _.clone(obj); 
    cloneObj.a.a = "change world" ; 
    cloneObj.a.b = 35; 
    cloneObj.b = 68 ; 
    console.log(obj); 
    //=>{a: {a: "change world", b: 35}b: 68} 
    console.log(cloneObj);  
    //=>{a: {a: "change world", b: 35}b: 68} 
    console.log(obj.a === cloneObj.a);
    //=>false
    

    ES解构

    var obj = { a: {a: "hello world", b: 31},b:34 }; 
    var cloneObj = {...obj}; 
    cloneObj.a.a = "change world"; 
    cloneObj.a.b = 35; 
    cloneObj.b = 68; 
    console.log(obj); 
    //=> {a: {a: "change world", b: 35}b: 34} 
    console.log(cloneObj); 
    //=> {a: {a: "change world", b: 35}b: 68} 
    console.log(obj.a === cloneObj.a); 
    //=>true
    

    深拷贝

    lodash的 _.cloneDeep

    var obj = { a: {a: "hello world", b: 31},b:34 }; 
    var cloneObj = _.cloneDeep(obj); 
    cloneObj.a.a = "change world" ; 
    cloneObj.a.b = 35; 
    cloneObj.b = 68 ; 
    console.log(obj); 
    //=> {a: {a: "hello world", b: 31}b: 34} 
    console.log(cloneObj); 
    //=> {a: {a: "change world", b: 35}b: 68} 
    console.log(obj.a === cloneObj.a); 
    //=> false
    

    JSON.parse(JSON.stringify(obj))

    var obj = { a: {a: "hello world", b: 31},b:34 }; 
    var cloneObj =JSON.parse(JSON.stringify(obj)); 
    cloneObj.a.a = "change world" ; 
    cloneObj.a.b = 35; 
    cloneObj.b = 68 ; 
    console.log(obj); 
    //=> {a: {a: "hello world", b: 31}b: 34} 
    console.log(cloneObj); 
    //=> {a: {a: "change world", b: 35}b: 68} 
    console.log(obj.a === cloneObj.a); 
    //=> false
    
  • 相关阅读:
    Code First 数据迁移 转
    WebAPI Post接收数据
    hbase1.2.4 API改动
    spark中RDD持久化浅析
    SQLSTATE[42S22]: Column not found: 1054 Unknown column 'Attr_id' in 'where clause'
    宝塔忘记面板地址怎么办? 可以找到没问题的
    卸载Apache 删除已经停止的服务
    Composer 卸载
    TP5.1模型 增删改查
    打印数据库int类型的时间戳
  • 原文地址:https://www.cnblogs.com/jj81/p/13669664.html
Copyright © 2011-2022 走看看