Handwritten deep copy, shallow copy

(1) Shallow copy

var obj1 = {
   name: 'zs',
   school: 'qq',
   major: {
     math: 'gs'
   }
}
var obj2 = obj1
obj1.major.math = 'zh'
console.log(obj2.major.math) // zh

Two objects point to the same reference address, one of them changes, the corresponding fields of the other objects will also change, this is a shallow copy

(2) Deep copy

The purpose of deep copy is: if one of them changes, the corresponding fields of the other objects will not change, and still maintain the original value. This is a deep copy. The principle of deep copy is to reopen memory space for the object and then refer to it. The object is copied cyclically and stored in a new memory

var obj1 = {
  name: 'zz',
  age: 23,
  arr: [1, 2, 3],
  major: {
    main: 'computer',
    other: 'math',
    majorArr: [1, 2, 3],
  }
}

// 深拷贝 针对数组和对象
function deepClone (target) {
  // 如果不是数组或者对象直接返回
  if (typeof target !== 'object') {
    return target
  }

  let newData;
  if (target instanceof Object) {
    newData = {}
  }
  if (target instanceof Array) {
    newData = []
  }

  for (let key in target) {
    // hasOwnProperty
    if (target.hasOwnProperty(key)) {
      newData[key] = deepClone(target[key]) // 递归!!对象的值是对象也需要处理
    }
  }
  
  return newData
}

var obj2 = deepClone(obj1)

obj1.major.other = 333
obj1.arr[0] = 344
obj1.major.majorArr[1] = 399 
console.log(obj2)
console.log(obj1)

It can be seen that obj1 is obj1, obj2 is obj2, and they do not affect each other. This is a deep copy

 

Guess you like

Origin blog.csdn.net/Luckyzhoufangbing/article/details/108580520