Public account: wechat search front end tool person; Take more dry goods
The difference between a deep copy and a shallow copy of an object is as follows:
Shallow copy
: copies only references to objects, not the objects themselves; Modified values affect each other;Deep copy
: copies all objects referenced by the copied object. Changing values does not affect each other.
Shallow copy
Object.assign()
Method is used to copy the values of all enumerable properties from one or more source objects to the target object. It will return the target object.- Details directly
https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Object/assign
.
function test() {
'use strict';
let obj1 = { a: 0 , b: { c: 0}};
let obj2 = Object.assign({}, obj1);
console.log(JSON.stringify(obj2)); // { a: 0, b: { c: 0}}
obj1.a = 1;
console.log(JSON.stringify(obj1)); // { a: 1, b: { c: 0}}
console.log(JSON.stringify(obj2)); // { a: 0, b: { c: 0}}
obj2.a = 2;
console.log(JSON.stringify(obj1)); // { a: 1, b: { c: 0}}
console.log(JSON.stringify(obj2)); // { a: 2, b: { c: 0}}
obj2.b.c = 3;
console.log(JSON.stringify(obj1)); // { a: 1, b: { c: 3}}
console.log(JSON.stringify(obj2)); // { a: 2, b: { c: 3}}
// Deep Clone
obj1 = { a: 0 , b: { c: 0}};
let obj3 = JSON.parse(JSON.stringify(obj1));
obj1.a = 4;
obj1.b.c = 4;
console.log(JSON.stringify(obj3)); // { a: 0, b: { c: 0}}
// Copy a single object
var obj = { a: 1 };
var copy = Object.assign({}, obj);
console.log(copy); // { a: 1 }
// Merge multiple objects
let o1 = { a: 1 };
let o2 = { b: 2 };
let o3 = { c: 3 };
let obj = Object.assign(o1, o2, o3);
console.log(obj); // { a: 1, b: 2, c: 3 }
console.log(o1); // {a: 1, b: 2, c: 3}, note that the target object itself also changes
}
// It is important to note that the shallow copy will change both itself and the target object.
test(a);
Copy the code
Deep copy
There are many ways to implement deep copy, from the simplest json.parse () method to the more common recursive copy method, as well as the object-create () method in ES5.
– Method 1: UseJSON.parse()
methods
function deepClone(initalObj) {
var obj = {};
try {
obj = JSON.parse(JSON.stringify(initalObj));
}
return obj;
}
var obj = {
a: {
a: "world".
b: 21
}
}
var cloneObj = deepClone(obj);
cloneObj.a.a = "changed";
console.log(obj.a.a); // "world"
Copy the code
Disadvantages:
- This method will discard the object
constructor
. So after a deep copy, whatever the original constructor of this object was, after a deep copy it’s going to be, okayObject
. - This method can only handle objects correctly
Number, String, Boolean, Array
, flat objects that can bejson
Directly represented data structures.RegExp
Objects cannot be deeply copied in this way.
– Method 2: Recursive copy
To avoid the situation where objects that refer to each other lead to an infinite loop, you should determine whether to refer to each other during traversal and exit the loop if so.
// Deep copy recursion 1.1
function deepClone(obj) {
var obj = {};
for (var i in initalObj) {
var prop = initalObj[i];
// Avoid an endless loop by referring to each other.
if(prop === obj) {
continue;
}
if (typeof prop === 'object') {
obj[i] = (prop.constructor === Array) ? [] : {};
arguments.callee(prop, obj[i]);
} else {
obj[i] = prop;
}
}
return obj;
}
Copy the code
// Deep copy recursion 1.2
function deepCopy(p, c) {
var c = c || {};
for (var i in p) {
if (typeof p[i] === 'object') {
c[i] = (p[i].constructor === Array) ? [] : {};
deepCopy(p[i], c[i]);
} else {
c[i] = p[i];
}
}
return c;
}
Copy the code
/ / deep copy recursive 1.3 write two more comprehensive way Reference to (https://mp.weixin.qq.com/s/vXbFsG59L1Ba0DMcZeU2Bg)
function forEach(array, cloneTarget) {
let index = -1;
const length = array.length;
while (++index < length) {
cloneTarget(array[index], index);
}
return array;
}
function clone(target, map = new WeakMap()) {
if (typeof target === 'object') {
const isArray = Array.isArray(target);
let cloneTarget = isArray ? [] : {};
if (map.get(target)) {
return target;
}
map.set(target, cloneTarget);
const keys = isArray ? undefined : Object.keys(target);
forEach(keys || target, (value, key) => {
if (keys) key = value
cloneTarget[key] = clone(target[key], map);
});
return cloneTarget;
} else {
return target;
}
}
Copy the code
2.3 Method 3: Set object.assign ()
/ / copy
function deepClone(initalObj) {
var obj = {};
for (var i in initalObj) {
var prop = initalObj[i];
// Avoid endless loops caused by cross-referencing objects
if(prop === obj) {
continue;
}
if (typeof prop === 'object') {
obj[i] = Object.assign(prop);
} else {
obj[i] = prop;
}
}
return obj;
}
Copy the code
Deep copy version 1.3 reference to: https://mp.weixin.qq.com/s/vXbFsG59L1Ba0DMcZeU2Bg (recursive method to summarize a comprehensive recommendation)