This is the third day of my participation in the August More text Challenge. For details, see:August is more challenging

Personal technical blog, wechat official account, video account and design portfolio of the blogger

Extending the operator (…) in ES6 Copy with object.assign () is a shallow copy, so called shallow copy and deep copy:

Shallow copy: During the copy process, the part of the traversal refers to the original address for the object/array type. Change any of the values and the other will change

Deep copy: A completely new memory address is created. Copy the object and its value, and the two objects modify any value of one without changing the other

1. Shallow copy

Shallow copy: Make only one outermost copy. If the copied object is a reference data type, the memory address is surrendered, so any modification to the reference data on the object that has been shallow-copied will affect the original rubbings

let obj = {
    a: 1.b: [1.2, {a:3}].c: {a:3}
}
obj.c.a = 4

let obj1 = {
    a: obj.a,
    b: obj.b
}
obj1.b.push(1) // Don't
obj1.b = 123This is reassigning rather than changing the original address of the objectconsole.log(obj.b) // will be changed
Copy the code

ES6 method:

let obj2 = Object.assign({},obj)
console.log(obj2)  // {a: 1,b: [1, 2, {a:3}],c:{a:4}The expansion operator:letobj3 = {... obj} conosle.log(obj3)// {a: 1,b: [1, 2, {a:3}],c:{a:4}
Copy the code

2. Deep copy

Deep copy: copy all the data inside and out, complete copy, ensure that the referenced data is still referenced, but do not take the address, just imitate your face, so there is no problem in extension, no conflict

let obj1 = {
    a: 1.b: [1.2, {a:3}].c: {a:3}}// Copy exactly. Copy perfectly, but copy one by one. It's too much trouble

obj1.c.a = 4

let obj2 = JSON.parse(JSON.stringify(obj1))
console.log(obj2)  // {a: 1,b: [1, 2, {a:3}],c:{a:3}
Copy the code

Homemade deep copy function

1. Pass in requirement 1 and output copies of rubbings

 let obj = { / / calligraphy
     a: 1.b: [1.2.3, {a: "我"}].c: {d: 5}}function extend (o1) {
     var obj1 = {}
     if (o1 instanceof Array) { // Check whether the object is an array
         obj1 = []
     }
     for(var key in o1){
         var value = o1[key] // The value in the rubbings
          // If the value is not null, you need to make a deep copy of the value object
         // obj1[key] = extend(value) 
         if(typeof value ==="object"&& value ! = =null){
             obj1[key] = extend(value) 
         }else{
             obj1[key] = value
         }
     }
     return obj1
 }

let obj2 = extend(obj)  // Deep copy test
obj2.b.push("Last")
console.log(obj2)
console.log(obj) // The deep copy does not affect the rubbings. The shallow copy rubbings change together
Copy the code