takeaway

  1. You need to understand data types first
  2. Distinguishes shallow copy from deep copy

The most common deep copy

JSON.parse(JSON.stringify());
Copy the code

Implementing deep copy

  1. recursive
  2. Do corresponding processing according to different types
  3. Handling circular references
/ / copy
function deepCopy(ori, hash) {
    const type = getType(ori);
    switch (type) {
        case 'object': return copyObject(ori, hash);
        case 'array': return copyArray(ori, hash);
        case 'date': return copyDate(ori);
        case 'regExp': return copyRegExp(ori);
        case 'element': return copyElement(ori);
        default: return ori;
    };
};
// Get the type
function getType(obj) {
    const str = Object.prototype.toString.call(obj);
    const map = {
        '[object String]': 'string'.'[object Boolean]': 'boolean'.'[object Number]': 'number'.'[object Undefined]': 'undefined'.'[object Null]': 'null'.'[object Symbol]': 'symbol'.'[object Object]': 'object'.'[object Array]': 'array'.'[object Date]': 'date'.'[object RegExp]': 'regExp'};if (obj instanceof Element) {
        return 'element';
    };
    return map[str];
};
// Copy objects
function copyObject(ori, hash = new WeakMap(a)) {
    let copy = {};
    // Hash is used to handle circular references
    if (hash.get(ori)) {
        return hash.get(ori);
    };
    hash.set(ori, copy);
    for (const [key, value] of Object.entries(ori)) {
        copy[key] = deepCopy(value, hash);
    };
    return copy;
};
// Copy the array
function copyArray(ori, hash = new WeakMap(a)) {
    let copy = [];
    if (hash.get(ori)) {
        return hash.get(ori);
    };
    hash.set(ori, copy);
    for (const [key, value] of Object.entries(ori)) {
        copy[key] = deepCopy(value, hash);
    };
    return copy;
};
// Copy the date
function copyDate(ori) {
    return new Date(ori);
};
// Copy the re
function copyRegExp(ori) {
    return new RegExp(ori);
};
// Copy the element
function copyElement(ori) {
    return ori.cloneNode(true);
};

// Test case
const obj1 = {
    name: 'kevin'.age: 30.address: {
        city: 'guangzhou'
    },
    arr: ['a'.'b'.'c'].brr: [].birth: new Date('1990-07-22'),
    sy1: Symbol("KK"),
    sy2: Symbol("KK"),};// Handle circular references
obj1.key = obj1;
obj1.brr[0] = obj1;


const obj2 = deepCopy(obj1);
obj2.age = 20;
obj2.address.city = 'shanghai';
obj2.arr[0] = 'a1';
obj2.birth = new Date(a);console.log(obj2.sy1 === obj2.sy2)
console.log(obj1);
console.log(obj2);
Copy the code

Deep copy thinking steps

  1. Object shallow copy
function clone(target) {
    let cloneTarget = {};
    for (const key in target) {
        cloneTarget[key] = target[key];
    }
    return cloneTarget;
};
Copy the code

Create a new object, iterate over the objects to be cloned, add the properties of the objects to be cloned to the new object, return.

  1. recursive
function clone(target) {
    if (typeof target === 'object') {
        let cloneTarget = {};
        for (const key in target) {
            cloneTarget[key] = clone(target[key]);
        }
        return cloneTarget;
    } else {
        returntarget; }};Copy the code
  1. Simply distinguish object arrays, other types are not extended here
function clone(target) {
    if (typeof target === 'object') {
        let cloneTarget = Array.isArray(target) ? [] : {};
        for (const key in target) {
            cloneTarget[key] = clone(target[key]);
        }
        return cloneTarget;
    } else {
        returntarget; }};Copy the code
  1. Handling circular references
function clone(target, map = new Map(a)) {
    if (typeof target === 'object') {
        let cloneTarget = Array.isArray(target) ? [] : {};
        if (map.get(target)) {
            return map.get(target);
        }
        map.set(target, cloneTarget);
        for (const key in target) {
            cloneTarget[key] = clone(target[key], map);
        }
        return cloneTarget;
    } else {
        returntarget; }};Copy the code

summary

I hope after reading this article you can have the following help:

  • Parse (json.stringify ()) is usually used as long as the definition of the data type is negotiated between the front and back ends. That’s it.
  • Implementing deep copy is more about reinforcing the various points of the implementation process,

If there are any mistakes in this article, please correct them in the comments section. If this article has helped you, please like it and follow it.