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

preface

Copying data is a common and routine operation, but sometimes it doesn’t work as expected

The article is relatively simple, more hope to watch while trying

Base type & reference type

The base type

  1. String
  2. Number
  3. .

Reference types

  1. Object
  2. Array

Pile & stack

The heap

  1. Dynamically allocating memory
  2. The memory size is not fixed
  3. Memory is not automatically freed

The stack

  1. Automatically allocate memory space
  2. The system automatically releases the memory

Shallow copy

Base types are managed separately, and reference types share the same address

Object.assign()

let obj1 = {
    a: 1,
    b: [1, 2]
}

let obj2 = Object.assign({}, obj1)

obj1.a = 2
obj1.c[0] = 2

console.log(obj1) // { a: 2, b: [2, 2] }
console.log(obj2) // { a: 1, b: [2, 2] }
Copy the code

Modify OBJ1. The base type does not change, but the reference type changes

Extended operators…

let arr1 = [1, [1, 2]]
let arr2 = [...arr1]
let arr3 = [].concat(arr1)

arr1[0] = 2
arr1[0][0] = 2
arr1.push(3)

console.log(arr1) // [2, [2, 2], 3]
console.log(arr2) // [1, [2, 2]]
console.log(arr3) // [1, [2, 2]]
Copy the code

A copy of the built-in Array method is a shallow copy

Deep copy

Base types and reference types are managed separately

JSON

let obj1 = {
    a: 1,
    b: [1, 2],
    c: () => {}
}

let obj2 = JSON.parse(JSON.stringify(obj1))

obj1.a = 2
obj1.b[0] = 2

console.log(obj1) // { a: 2, b: [2, 2], c: () => {} }
console.log(obj2) // { a: 1, b: [1, 2] }
Copy the code

When obj1 is modified, the base and reference types of obj2 are unchanged, but obj2.c is missing. Result from json.stringify () data processing

Using json.parse () requires the package to try catch, since this error will cause the program to terminate

recursive

let obj1 = {
    a: 1,
    b: {
        b1: 1
    }
}

let obj2 = deepFun(obj1)

obj1.a = 2
obj1.b.b1 = 2

console.log(obj1) // { a: 2, b: { b1: 2 } }
console.log(obj2) // { a: 1, b: { b1: 1 } }

function deepFun(obj) {
    let objc = {}
    for (const key in obj) {
        if (typeof obj[key] === 'object') {
            objc[key] = deepFun(obj[key])
        } else {
            objc[key] = obj[key]
        }
    }
}
Copy the code

The above is a recursive deep copy implementation of pure objects. The main idea here is to consider other variable types

conclusion

  1. The difference between a shallow copy and a deep copy is whether reference data is processed

  2. Both types of copying are possible during development, and learning to understand the concepts of both can take us from being confused by copying to being a beneficiary of copying