Shallow copy 🐚

For basic data types, number, Boolean, string, null, and undefined), copy is the value of the data for the reference data types (object), copy the data memory address 😥

Basic data types 🌰 let fistName = 'Tom' let lastName = 'Alice' console.log(fistName) // Tom console.log(lastName) // AliceCopy the code

New memory is created for lastName, corresponding to the stack structure:

The variable name A variable’s value
fistName Tom
lastName Tom —- Alice

So changing the value of lastName has no effect on fristName 👍

Reference data type 🌰 let person = {name: 'Bob', age:12 } let myInfo = person myInfo.name = 'myName' console.log(myInfo.name) // myName console.log(person.name) // myNameCopy the code
The stack The heap
Variable name Value of a variable A variable’s value
Address of the person {name:'Bob',age:12}{name:'myName',age:12}
myInfo Address (pointing to the variable value of Person in the heap)

Myinfo.name = myinfo.name = myinfo.name = myinfo.name = myinfo.name = myinfo.name = myinfo.name = myinfo.name = myinfo.name = myinfo.name = myinfo.name = myinfo.name = myinfo.name = myinfo.name = myinfo.name = myinfo.name = myinfo.name = myinfo.name = myinfo.name = myinfo.name

Deep copy 🐚 🐚

In contrast to shallow copy, deep copy requires copying the values in the heap in reference data types and creating new heap space

Or the above 🌰, after deep copy

The stack The heap
Variable name Value of a variable A variable’s value
Address of the person {name:'Bob',age:12}
myInfo address {name:'myName',age:12}

At this point, change myInfo’s own heap variable value, leaving Person unaffected

Implementing deep copy
  1. We only need to process data of reference type

  2. If the reference type is nested in multiple layers {data:{name:’Tom’}}, recursive judgment is required

    const deepClone = (param) => { let type = Object.prototype.toString.call(param).slice(8, Let result = type === 'Array'? [] : {} if (type === 'Object' || type === 'Array') { for (let itme in param) { if (param.hasOwnProperty(itme)) { result[itme] = deepClone(param[itme]) // Recursive call}}} else {result = param} return result} let person = {name: 'Bob', age: 12, data:{ hh:'123' } }Copy the code