Deep copy
1. The JSON conversion:
var targetObj = JSON.parse(JSON.stringify(copyObj))
let arr4 = JSON.parse(JSON.stringify(arr))
Copy the code
Disadvantages:
- If an object has a function in it, the function cannot be copied
- Unable to copy properties and methods on the copyObj object prototype chain
- When the data level is very deep, stack overflow occurs
2. Ordinary recursive functions:
function deepCopy( source ) {
if(! isObject(source))return source; // Return if it is not an object
let target = Array.isArray( source ) ? [] : {} // Array compatibility
for ( let k in source ) {
if (source.hasOwnProperty(k)) {// Copy only the properties of the object itself
if ( typeof source[ k ] === 'object' ) {
target[ k ] = deepCopy( source[ k ] )
} else {
target[ k ] = source[ k ]
}
}
}
return target
}
function isObject(obj) {
return typeof obj === 'object'&& obj ! = =null
}
Copy the code
Disadvantages:
- Unable to hold a reference
- When the data level is very deep, stack overflow occurs
3. Anti-stack overflow function:
function cloneLoop(x) {
const root = {};
/ / stack
const loopList = [
{
parent: root,
key: undefined.data: x,
}
];
while(loopList.length) {
// Depth first
const node = loopList.pop();
const parent = node.parent;
const key = node.key;
const data = node.data;
// Initialize the assignment target. If key is undefined, copy it to the parent element, otherwise copy it to the child element
let res = parent;
if (typeofkey ! = ='undefined') {
res = parent[key] = {};
}
for(let k in data) {
if (data.hasOwnProperty(k)) {
if (typeof data[k] === 'object') {
// Next loop
loopList.push({
parent: res,
key: k,
data: data[k],
});
} else{ res[k] = data[k]; }}}}return root;
}
Copy the code