Only deep clones of arrays and objects
DeepClone method
function deepClone(arr=undefined,spaceM=new Map(a)) {
if (typeof (arr) == "object") {
// The arR in a recursion is an array or an object
// Start a shallow clone with the expansion operator
let newArray = Array.isArray(arr) ? [...arr] : { ... arr };// Start with Map to prevent cyclic reference clones and stack overflow.
// Where key stores arR and value stores newArray, return terminates further for in loops when arR has been stored in map
if (spaceM.get(arr)) {
return spaceM.get(arr);
}
spaceM.set(arr,newArray)
// End of code A
for (const index in arr) {
if (typeof (arr[index]) == "object") {// Find a reference object, perform recursive deepClone clone
newArray[index] = deepClone(arr[index],spaceM)
}
}
return newArray
} else {
return arr
}
}
Copy the code
Note
- Shallow clone with expansion operator
- The for in loop looks at references in shallow clones, cloning again recursively
- In subrecursion, the new newArray is returned, that is, deepClone(arr[index], spaceM) opens a new space, returns a new reference, assigns a value to newArray[index], and the deepClone is complete
- For example, A’s next points to B, B’s next points to A, and Map is used to prevent continuous recursive cloning. The final map key is the reference node of the old ARR, and the value is the reference node of the new ARR
test
Testing a
let space = new Map(a)let arr = [
// {a:1,b:2},
2[1.2.3]."fae"
]
let newArray = deepClone(arr, space)
console.log(newArray)
console.log(space)
Copy the code
Test two
let space = new Map(a)let arr1 = {
a: 1.b: 1.d: {
a: 1.b: 1
},
c: 1.f: [{a: 1.b: 2 },
2[1.2.3]."fae"]}let newArray = deepClone(arr1, space)
console.log(newArray)
console.log(space)
Copy the code
Test three
let space = new Map(a)let A = {}
let B = {}
A.next = B
A.x = 12
B.next = A
B.x = 13
let newArray = deepClone(A, space)
console.log(newArray)
console.log(space)
Copy the code