当前位置:网站首页>The difference between deep copy and shallow copy

The difference between deep copy and shallow copy

2022-06-12 08:37:00 Month to month better

1、 Shallow copy

Shallow copy copies only the reference of an object , Instead of copying the object itself , New and old objects still share the same block of memory

2、 Deep copy

Deep copy creates an identical object , The new object and the original object do not share memory , Modifying the new object will not change the original pair of objects .

Two 、 Method

1、 Shallow copy

a、Object.assign()

Object.assign() Method can copy the enumerable properties of any multiple source objects to the target objects , Then return the target object .Object.assign() Copy the reference of the object's properties , Not the object itself .
 Insert picture description here
2、 Deep copy

a、JSON transformation

let newObj = JSON.parse(JSON.stringify(obj));
shortcoming :

  1. If the object has a function , Functions cannot be copied

2) Cannot copy properties and methods on the object prototype chain

3) When the level of data is very deep , Stack overflow

b、 Recursive function

function deepClone(obj){
    
      let tempObj = obj.constructor ===Array ? [] : {
    }
          for (let keys in obj) {
    
              if(obj.hasOwnProperty(keys)) {
    
                  if (obj[keys] && typeof obj[keys] === "object") {
    
                      tempObj[keys] = deepClone(obj[keys])
                  } else {
    
                      tempObj[keys] = obj[keys]
                  }
              }
          }

     return tempObj
  }

shortcoming :

1) Unable to save reference

2) When the data level is very deep , Stack overflow

原网站

版权声明
本文为[Month to month better]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/163/202206120828077314.html