“This is the 26th day of my participation in the First Challenge 2022. For details: First Challenge 2022”

Deep copy

introduce

The last article talked about shallow copies, so naturally there will be deep copies.

Shallow copy copies only the first layer of the reference type, or only the pointer of the reference type, and does not copy all the reference type data stored in the heap memory.

So the emergence of deep copy, is to solve the existence of shallow copy above.

Deep copy

Here are the common deep-copy methods

  • JSON.stringify()

It can be copied by JSON method, which is one of the most commonly used JS deep copy methods at present.

By using two methods of JSON, json.stringify and json.parse

Parse (json.stringify (obj)) for deep copy.

But there are problems: for example

  • Cannot deeply copy a bigint from a base type

    An error will be reported, which is the point to pay attention to

  • It also cannot handle undefined, symbol, and NaN values

    As you can see, the result will be null

  • Unable to handle functions and re’s

    When dealing with functions and re, the results are different

    • Changes the function to NULL

    • Turns the re into an empty object {}

        const arr3 = [
          () = > {
            console.log(123)},/ ^ [0-9] * $/,]Copy the code

    The results for

    [ null, {} ]
    Copy the code
  • Deep copy implementation

    Deep copy is done by cyclic recursion

    If string number Boolean is undefined, return the current value of the data type

    Return null, function, regexp, data, etc.

    Note that symbols are not enumerable, so use getOwnPropertySymbols to do this.

    const deepCopy = (object) = > {
      if(! object ||typeofobject ! = ='object') return
    
      let newObject = Array.isArray(object) ? [] : {}
    
      for (let key in object) {
        if (object.hasOwnProperty(key)) {
          newObject[key] = typeof object[key] === 'object' ? deepCopy(object[key]) : object[key]
        }
      }
    
      return newObject
    }
    Copy the code

conclusion

Deep copy is an exact copy of a value of a primitive data type. It is also possible to copy all data values of reference types.

Returns a new value that is exactly the same as the copied data.