This is the first day of my participation in the Gwen Challenge in November. Check out the details: the last Gwen Challenge in 2021

Shallow copy

  • Shallow copy is the creation of new data that has original properties worth copying
  • The base type copies the value of the base type
  • Reference types copy memory addresses
    // Implement a simple shallow copy
    let clone = (obj) = > {
        let newObj = {}
        for(let prop in obj) {
            if(obj.hasOwnProperty(prop)){
                newObj[prop] = obj[prop]
            }
        }
        return newObj
    }
Copy the code
  • Shallow copy exists
  • Object.assign
  • Used to assign the values of all enumerable properties from one or more source objects to the target object. It will return the target object
    let obj = {
        a:1
        b:2
    }

    let objs = Object.assign({}, obj) // {a:1,b:2}
Copy the code
  • slice
  • Returns a new array object. This object is a new array objectbegin 和 endDetermines a shallow copy of the original array
    let arr = [1.2.3]
    let arr1 = arr.slice(0) / / [1, 2, 3]
    arr1[0] = 6
    arr  / / [6, 2, 3]
    arr1 / / [1, 2, 3]
Copy the code
  • concat
  • Used to merge multiple arrays to return a new array without changing the original array
    let arr = [1.2.3]
    let arr1 = arr.concat() / / [1, 2, 3]
    arr1[0] = 6
    arr1 / / [6, 2, 3]
    arr  / / [1, 2, 3]
Copy the code
  • Extended operator.
    let arr = [1.2.3]
    let arr1 = [...arr]
    arr1[0] = 6
    arr1 / / [6, 2, 3]
    arr  / / [1, 2, 3]
Copy the code

Deep copy

  • Deep copy opens a new stack corresponding to two different addresses
  • Common deep copy
  • _.cloneDeep()
    let _ = require('lodash')
    let obj = {
        a:1
        b: {c:1}}let obj2 = _.cloneDeep(obj)
    console.log(obj.b.c == obj1.b.c)  // false
Copy the code
  • JSON.stringify
  • Converts a JavaScript object or value to a JSON string
  • The undefined symbol and function are ignored
let obj = {a:1}
let obj1 = JSON.stringify(obj) // '{"a":1}'
Copy the code

Write a deep copy by hand

let cloneDeep = (obj,hash = new WeakMap(a)) = > {
    // If obj is null or undefined, no copy operation is performed
    if(obj === null) return obj
    // If obj is a prototype of an instance object, return the processed obj directly
    if(obj instanceof Date) return new Date(obj)
    if(obj instanceof RegExp) return new RegExp(obj)
    // If it is a function, no deep copy is required
    if(typeofobj ! = ="object" ) return obj
    // Deep-copy object returns the element specified by WeakMap
    if(hash.get(obj)) return hash.get(obj)
    let cloneObj = new obj.constructor()
    // Find the constructor on the owning class prototype
    hash.set(obj,cloneObj)
    for (let key in obj) {
        if(obj.hasOwnProperty(key)){
            // Implement a recursive copy
            cloneObj[key] = cloneDeep(obj[key],hash)
        }
    }
        return cloneObj
}
Copy the code

conclusion

  • Today’s lesson