JS-deep copy

Foreword:

A simple data type is stored in the stack space and a value is stored;
if it is a complex data type, it is stored in the heap space, and the reference is stored in the stack. It is this difference in storage methods that leads to the difference between shallow copy and deep copy.

Shallow copy:
If the attribute is a basic type, the value of the basic type is copied. If the attribute is a reference type, the copy is the memory address, so modifying the newly copied object will affect the original object.
Deep copy:
A complete copy of an object from the memory, a new area is opened from the heap memory to store the new object, and the modification of the new object will not affect the original object.

The commonly used way to implement deep copy
数组.concat() can only achieve the first layer of deep copy, and the deep layer cannot be achieved.
Object.assign()Same as above,
JSON.parse(JSON.stringify())only supports object, array, string, number, true, false, null data, and other data such as functions, undefined, Date, Data types such as RegExp are not supported. For data that it does not support, this attribute will be ignored directly.

Recursively implement deep copy of objects or arrays

var My={
    
    
    name:'123',
    age:22,
    hobby:['吃饭','睡觉','打游戏'],
    study:{
    
    
        js:{
    
    
            vue:'双向数据绑定',
            react:'组件化开发'
        },
        html:{
    
    
            h5:{
    
    div:'语义化标签',input:'增强型表单'}
        }
    }
}
let My2=My      //浅拷贝,复制的是地址
// My2.age=10   
// console.log(My);
// console.log(My2);

function deepClone(obj){
    
    
    //传入初始参数
    //如果不是对象或数组就返回,是null空对象也返回
    if((typeof obj)!='object'||obj==null){
    
      
        return obj
    }
    //初始化返回结果
    let result;
    //判断是不是数组
    if(obj instanceof Array){
    
    
        result=[]
    }else if(obj instanceof Object){
    
    
        result={
    
    }
    }
    
    for (let key in obj){
    
       //for in 遍历对象,遍历的是key
        //判断key不是原型上的属性 hasOwnProperty方法 如果属性在原型上会返回false
        if(obj.hasOwnProperty(key)){
    
    
            //递归函数 使用循环把每个参数传入然后重复调用 循环完毕函数执行完毕
            result[key]=deepClone(obj[key])
        }
    }

    //返回结果
    return result;

}
// console.log(deepClone(My));
//深拷贝 在内存中开辟了新的空间,复制的对象地址指向新的地址
My2=deepClone(My)
My2.age=12
console.log(My);
console.log(My2);

Function copy

function deepClone(target){
    
    
  if(target instanceof Object){
    
    
      let dist ;
      if(target instanceof Array){
    
    
        dist = []
      }else if(target instanceof Function){
    
    
        dist = function(){
    
    
            // 在函数中去执行原来的函数,确保返回的值相同
            return target.call(this, ...arguments);
        }
      }else{
    
    
        dist = {
    
    };
      }
      for(let key in target){
    
    
          dist[key] = deepClone(target[key]);
      }
      return dist;
  }else{
    
    
      return target;
  }
}

Regular copy


function deepClone(target){
    
    
  if(target instanceof Object){
    
    
      let dist ;
      if(target instanceof Array){
    
    
        // 拷贝数组
        dist = [];
      }else if(target instanceof Function){
    
    
        // 拷贝函数
        dist = function () {
    
    
          return target.call(this, ...arguments);
        };
      }else if(target instanceof RegExp){
    
    
        // 拷贝正则表达式
       dist = new RegExp(target.source,target.flags);
      }else{
    
    
        // 拷贝普通对象
        dist = {
    
    };
      }
      for(let key in target){
    
    
          dist[key] = deepClone(target[key]);
      }
      return dist;
  }else{
    
    
      return target;
  }
}

Copy date

作者:海因斯坦
链接:https://zhuanlan.zhihu.com/p/270332499
来源:知乎
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

function deepClone(target){
    
    
  if(target instanceof Object){
    
    
      let dist ;
      if(target instanceof Array){
    
    
        // 拷贝数组
        dist = [];
      }else if(target instanceof Function){
    
    
        // 拷贝函数
        dist = function () {
    
    
          return target.call(this, ...arguments);
        };
      }else if(target instanceof RegExp){
    
    
        // 拷贝正则表达式
       dist = new RegExp(target.source,target.flags);
      }else if(target instanceof Date){
    
    
          dist = new Date(target);
      }else{
    
    
        // 拷贝普通对象
        dist = {
    
    };
      }
      for(let key in target){
    
    
          dist[key] = deepClone(target[key]);
      }
      return dist;
  }else{
    
    
      return target;
  }
}

Final function

function deepClone(target,cache = new Map()){
    
    
  if(cache.get(target)){
    
    
      return cache.get(target)
  }
  if(target instanceof Object){
    
    
      let dist ;
      if(target instanceof Array){
    
    
        // 拷贝数组
        dist = [];
      }else if(target instanceof Function){
    
    
        // 拷贝函数
        dist = function () {
    
    
          return target.call(this, ...arguments);
        };
      }else if(target instanceof RegExp){
    
    
        // 拷贝正则表达式
       dist = new RegExp(target.source,target.flags);
      }else if(target instanceof Date){
    
    
          dist = new Date(target);
      }else{
    
    
        // 拷贝普通对象
        dist = {
    
    };
      }
      // 将属性和拷贝后的值作为一个map
      cache.set(target, dist);
      for(let key in target){
    
    
          // 过滤掉原型身上的属性
        if (target.hasOwnProperty(key)) {
    
    
            dist[key] = deepClone(target[key], cache);
        }
      }
      return dist;
  }else{
    
    
      return target;
  }
}

本文代码作者:海因斯坦
链接:https://zhuanlan.zhihu.com/p/270332499
来源:知乎
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

Guess you like

Origin blog.csdn.net/weixin_51198863/article/details/111808667