What is deep copy and shallow copy?

Copy is assignment. To assign one variable to another is to copy the contents of the variable. To assign the value of one object to another is to make a copy of an object.

ShallowCopy simply adds a pointer to an existing memory address

A deepCopy adds a pointer to a new memory and makes the pointer point to the new memory.

Shallow copy

Var a = [1, 2, 3, 4]. var b = a; b.push(5); console.log(a); / / [1, 2, 3, 4, 5]. The console log (b); / / [1, 2, 3, 4, 5]Copy the code

The code above is a simple example of a shallow copy. Both A and B are reference types and use address passing. That is, a passes the address to B, so a and B must refer to the same address (the address of the reference type is stored in stack memory), and this address refers to the value of the reference type in heap memory. When B changes this value, it also changes a’s value, because a’s address also points to this value. I see a very visual explanation, like a rented a room, gave the address of the room to B, B found the room by the address, then any changes B made to the room (adding some green plants) must also be visible to A.

Deep copy

Var obj1 = {name: "li ", age: 36, wife: {name: 'li ', son: {name:' li '}}}; var obj2 = {}; function copy(obj1, obj2) { for (var i in obj1) { if (obj1[i] instanceof Array) { obj2[i] = []; copy(obj1[i], obj2[i]) }else if(obj1[i] instanceof Object){ obj2[i]={}; copy(obj1[i], obj2[i]) }else{ obj2[i]=obj1[i] } } } copy(obj1,obj2); Obj1. The wife. Name = 'small'; Obj2. The wife. Son. Name = 'Ming'; console.log(obj2); console.log(obj1);Copy the code

Attached: screenshot of results

The obj1.wife. Name property has changed to ‘small’, while the obj2.wife. Name property has not changed; The property value of obj2.tume.son. name has changed to ‘Xiaoming’, while the property value of obj1.tume.son. name has not changed.

summary

Deep and shallow copies are not hard to understand, just deep enough to copy. For example, we want to copy b. bj to a, shallow copy is only copy Reference, copy a. bj === B. bj deep copy is to create a “identical” object, and save in a. bj, so a. bj! == b.objps: For reference types, the === operator returns true if the lvalue and rvalue are the same object, i.e. the same memory address.