The method of front-end implementation of shallow copy and deep copy

Shallow copy means that only one layer is copied when the object is copied. When the data of the source object changes, the data of the new object will also change.

Deep copy refers to copying all levels of the object. When the data of the source object changes, the data of the new object will not change
 

1. JSON.parse(JSON.stringify()) can copy both arrays and objects but cannot copy functions ( deep copy )

let arr1 = [1, 2, false, {a: 1}]
let arr2 = JSON.parse(JSON.stringify(arr_1))

2. Recursive copy only supports objects ( deep copy )

function deepCopy(obj) {
  if (typeof obj !== 'object') return;
  // 根据obj的类型判断是新建一个数组还是一个对象
  const newObj = obj instanceof Array ? [] : {};
  for (let key in obj) {
    // 遍历obj,并且判断是obj的属性才拷贝
    if (obj.hasOwnProperty(key)) {
      // 判断属性值的类型,如果是对象递归调用深拷贝
      newObj[key] = typeof obj[key] === 'object' ? deepCopy(obj[key]) : obj[key];
    }
  }
  return newObj;
}

3. Use $.extend in jquery (when the parameter is true, it is a deep copy , otherwise it is a shallow copy )

let arr1 = [[1,1], 2, 3, 4];
let arr2= []
$.extend(true,arr2,arr1)

4. Concat and slice copy a simple array as a deep copy , otherwise it is a shallow copy

//支持
let arr1 = [1, 2, false, 'a']
let arr2 = [].concat(arr1)

let arr3 = [1, 2, 3, 4];
let arr4 = origin.slice()

//不支持
let arr1 = [1, 2, {a:1}, 'a']
let arr2 = [].concat(arr1)

let arr3 = [1, 2, {a:1}, 4];
let arr4 = origin.slice()

5. The extension operator of es6 copies the value of the first layer to a deep copy , otherwise it is a shallow copy

//支持
let arr1 = [1,2,3]
let arr2 = [...arr1]

let obj1 = {a:1,b:2}
let obj2 = {...obj1}

//不支持
let arr1 = [1,2,[11,22]]
let arr2 = [...arr1]

let obj1 = {a:1,b:{c:2}}
let obj2 = {...obj1}

6. Object.assign copy the value of the first layer is a deep copy , otherwise it is a shallow copy (only for objects)

//支持
let obj1 = {a:1,b:2}
let obj2 = {...obj1}

//不支持
let obj1 = {a:1,b:{c:2}}
let obj2 = {...obj1}

7. Assignment is a shallow copy

let obj1 = {a:1,b:2}
let obj2 = obj1

Guess you like

Origin blog.csdn.net/Lucky_girl_wan/article/details/126972687