The three implementations of deep copy are:
Recursively copy all hierarchical properties recursively
deepClone(obj) { let objClone = Array.isArray(obj) ? [] : {} if (obj && typeof obj === 'object') {for (let key in obj) {if (obj. HasOwnProperty (key)) { If (obj[key] && typeof obj[key] === 'object') {objClone[key] = this.deepClone(obj[key])} else {// If (obj[key] === 'object'); Obclone [key] = obj[key]}}}} return objClone}Copy the code
2. In addition to recursion, we can also borrow parse and Stringify from JSON objects
function deepClone(obj){ let _obj = JSON.stringify(obj), objClone = JSON.parse(_obj); Return objClone} let a=[0,1,[2,3],4], b=deepClone(a); a[0]=1; a[2][0]=1; console.log(a,b);Copy the code
3. Borrow JQ’s extend method
$.extend( [deep ], target, [object1 , objectN ] )
Deep indicates whether it is a deep copy. If true, it is a deep copy. If false, it is a shallow copy
Target Object Type Target Object to which member attributes of other objects will be attached.
Object1 objectN Optional. Object The first and NTH objects of type to be merged.
Let a = [0, 1, 2, 3], 4), b = $. The extend (true, [], a); a[0]=1; a[2][0]=1; console.log(a,b);Copy the code