Shallow copy
1. The concept
In JavaScript, copying generally refers to the process of copying variables.
For simple types, copying is a straightforward assignment;
For complex types, shallow copy is the process of copying the reference address of an object. If you modify an attribute of the source object, the attribute of the target object will be changed because the reference is the same.
2. The test
/ / test 1
function test() {
var obj = {
id: 1.name: 'Tom'.props: {
age: 18,},color: ['red'.'green']};const res = copy(obj);
obj.props.age = 20; // Modify the property value of the original object and check whether the target object is affected
console.log(res.props.age === 20); // true // Indicates that the target object is affected
}
Copy the code
3. The implementation
function copy(source) {
let res = {};
for (const key in source) {
res[key] = source[key];
}
return res;
}
Copy the code
Deep copy
1. The concept
For complex types, shallow copy refers to copying a completely new object, modifying the properties of the original object without affecting the target object. Because the two copied objects have different references, that is, different addresses pointing to memory.
2. The test
function test() {
var obj = {
id: 1.name: 'Tom'.props: {
age: 18,},color: ['red'.'green']};let res = deepCopy(obj);
obj.props.age = 20; // Modify the property value of the original object and check whether the target object is affected
console.log(res.props.age === 18); // true // Indicates that it is not affected
}
Copy the code
3. The implementation
/ / the first edition
function deepCopy(target, source) {
for (const key in source) {
const item = source[key];
if (Array.isArray(item)) {
target[key] = [];
deepCopy(target[key], item);
} else if (typeof element === 'object') {
target[key] = {};
deepCopy(target[key], item);
} else{ target[key] = item; }}}Copy the code
On closer inspection, the first version has a lot of redundant code.
/ / the second edition
function deepCopy(target, source) {
for (const key in source) {
const item = source[key];
if (typeof item === 'object') {
deepCopy(Array.isArray(target[key]) ? [] : {}, item);
} else{ target[key] = item; }}}Copy the code
Third, summary
-
If you have a known object with properties of simple types, you can implement deep copy with json.parse (json.stringify (source))
-
However, if the original object has properties of complex types such as functions, dates, re, etc., the problem of attribute loss will occur after the conversion
-
The root cause of this problem is that JSON does not support these complex types, as explained here.
// Test JSON deep copy
function test() {
var obj = {
name: 'bird'.speak: function() {
console.log('ji ji ji')}}let res = deepClone(obj);
console.log(res.speak); // undefined // indicates that the method attribute is missing
}
function deepClone(source) {
return JSON.parse(JSON.stringify(source));
}
Copy the code