What are the methods to achieve deep and shallow copy?

Reference: Several methods of js shallow copy and deep copy

1. Shallow copy

(1) Object.assign()

Reference: Object.assign() usage explanation

var obj1 = {a: 1, b: 2};
var obj2 = Object.assign({}, obj1);
(2) Destructuring assignment
var obj1 = {a: 1, b: 2};
var obj2 = {...obj1};

Principle of Shallow Copy:

function shallowCopy(obj) {
  var target = {};
  for (let i in obj) {
    if (obj.hasOwnproperty(i)) {
      target[i] = obj[i];
    }
  }
  return target;
}

2. Deep copy

(1) Use JSON.parse and JSON.stringfy
var obj1 = {
  name: 'li',
  hobit: ['摄影', '羽毛球']
}
var obj2 = JSON.parse(JSON.stringify(obj1));
obj2.hobit.push('游泳');
console.log(obj1); //{ name: 'li', hobit: [ '摄影', '羽毛球' ] }
console.log(obj2); //{ name: 'li', hobit: [ '摄影', '羽毛球', '游泳' ] }
(2) Use recursion to achieve

There are also many limitations when using JSON.parse and JSON.stringfy: Reference: pitfalls that should be paid attention to about JSON.parse(JSON.stringify(obj)) implementing deep copy

  1. If there is a time object in obj, then the result of JSON.parse after JSON.stringify, the time will only be in the form of a string. Not a time object;
  2. If there are RegExp and Error objects in obj, the result of serialization will only get empty objects;
  3. If there is a function in obj, undefined, the result of serialization will lose the function or undefined;
  4. If there are NaN, Infinity and -Infinity in obj, the result of serialization will become null
  5. JSON.stringify() can only serialize the enumerable own properties of the object. For example, if the object in obj is generated by a constructor, then use JSON.parse(JSON.stringify(obj)) after deep copying. The constructor of the discarded object;
  6. If there are circular references in the object, deep copy cannot be implemented correctly;

A deep copy can be achieved through recursion:

function deepCopy(obj) {
  if (obj == null)  return obj;
  if (obj instanceof Date) return new Date();
  if (obj instanceof RegExp) return new RegExp(obj);
  if (typeof obj !== 'object') return obj;
  let cloneObj = new obj.constructor();
  for (let i in obj) {
    if (obj.hasOwnproperty(i)) {
      cloneObj[i] = deepCopy(obj[i]);
    }
  }
  return cloneObj;
}
(3) jQuery extend
$.extend( [deep ], target, object1 [, objectN ] )
  • deep : Indicates whether to deep copy, true for deep copy, false for shallow copy
  • target : Object type target object, member properties of other objects will be attached to this object
  • object1... objectN : The first and Nth objects of the Object type to be merged.

Guess you like

Origin blog.csdn.net/weixin_43912756/article/details/108611267