Deep copy and shallow copy

JavaScript has two types of data

  1. Basic data type: String Number Boolean null un______ symbol
  2. Reference type: Object Arrat Function

There is no deep or light copy for basic data types, stored in the stack area of memory. Reference types are generally stored in the heap, and reference Pointers are stored in the stack and point to the reference itself. Both deep and shallow copies are equivalent to reference types.

Shallow copy

Two JS objects point to the same memory address

  1. Simple assignment
let obj = {
    parent: {
        children: "hello"
    },
    value: 12
}
let newObj = obj;
newObj.value = 24;
newObj.parent.children = "hello world";
console.log(obj)//{"parent": {"children": "hello world"}"value":24}

Copy the code
  1. Object.assign(): The first layer is a deep copy, and the other layers are just shallow copies
let obj = {
    parent: {
        children: "hello"
    },
    value: 12
}
let newObj = Object.assign({}, obj);
newObj.value = 24;
newObj.parent.children = "hello world";
console.log(obj)//{"parent": {"children": "hello world"},"value": 12}
Copy the code
  1. $.extand({}, obj): jQuery plugin
  2. Concat, slice, etc., for multiple reference types, if it is a one-dimensional array is actually a deep copy

Deep copy

The modification does not affect each other. The copied object points to a new memory address

  1. Manual assignment
let obj = {
    parent: 'hello'.value: 12
}
let newObj = { parent: obj.parent,value: obj.value};
Copy the code
  1. Object.assign(): same usage as above, applies to deep copy with only one dimension
  2. $.extand(true, {}, obj):
  3. Json.parse (json.stringify (obj)): two dimensions and above
  4. _. Clone (obj, true) or _. CloneDeep (obj) in the Lodash library: two or more dimensions
npm install lodash
"
import * as _ form 'lodash';
Copy the code
  1. Traversal and judge assignment obj.hasOwnProperty(key)