Simple version:

const newObject = JSON.paese(JSON.stringfy(oldObj))
Copy the code

Limitations:

  • Special objects such as functions and regexps cannot be cloned

  • Object constructor is not discarded; all constructors refer to Object

  • An error is reported when an object has a circular reference

    const a = {val:2};
    a.target = a;
    Copy the code

    Copying A will result in stack overflow because of infinite recursion.

The full version:

function deepClone(obj) {
    if(typeofobj ! == object || obj ===null) {
        return obj
    }
    let newObj = {}
    if (Array.isArray(obj)) { // It is an array
        newObj = []
    }
    for (let key in obj) {
        if (obj.hasOwnProperty(key)) {
            newObj[key] = deepClone(obj[key]) // If it is an object, it is deeply traversed, if it is not an object, it is directly returned}}return newObj
}
Copy the code