The introduction
Both shallow and deep copies are copies for reference types
Shallow copy
Shallow copy refers to copying only the reference to the heap address
var arr = [1.2.3];
var arrs = arr; / / copy
arrs.push(4); // Modify the copy
console.log(arr); // [1, 2, 3, 4] ArR also changes
Copy the code
Deep copy
Create a new space in the heap, copy the value of the original object into the new space, and reference to the new address
var arr = [1.2.3];
var arrs = JSON.parse(JSON.stringify(arr)); / / copy
arrs.push(4); // Modify the copy
console.log(arr); // [1, 2, 3] arR does not change
console.log(arrs); // [1, 2, 3, 4]
Copy the code
Object deep copy method
1. JSON method
Disadvantages: undefined cannot be copied, function cannot be copied
function deepClone(obj) {
return JSON.parse(JSON.stringigy(obj));
}
Copy the code
2. Recursion also applies to deep copies of arrays
function deepClone(obj){let objClone = Array.isArray(obj) ? [] : {}; // Check if it is an array
if (obj && typeof obj === 'object') { // Make sure it is a reference type
for(let key inobj){if (obj[key] && typeof obj[key] === 'object') {// Determine if there is deep nestingObjClone [key] = deepClone (obj [key]); }else{objClone[key] = obj[key]}}}return objClone;
}
Copy the code
3, the Object. The assign (target,… sources)
Disadvantages: Only level 1 attributes can be deeply copied, and properties above level 2 are shallow copied
function deepClone(obj,sources) {
return Object.assign(obj, ... sources)// obj: target object sources: source object
}
Copy the code
Extend of jquery
// Deep copy, target data source, object Object to merge
$.extend( [deep ], target, object1 [, objectN ] )
Copy the code
Array deep copy
1, the for
function deepCloneArr(arr) {
let res = [];
for(let i = 0; i < arr.length; i ++){
res.push(arr[i])
}
return res;
}
Copy the code
2, concat ()
function deepCloneArr(arr) {
return [].concat(arr);
}
Copy the code
3, slice ()
function deepCloneArr(arr) {
return arr.slice();
}
Copy the code
4, JSON
function deepCloneArr(arr) {
return JSON.parse(JSON.stringigy(arr));
}
Copy the code
5, extension operators…
function deepCloneArr(arr) {
return [...arr];
}
Copy the code