current position:Home>The difference between shallow copy and deep copy is to use native JavaScript to realize deep copy

The difference between shallow copy and deep copy is to use native JavaScript to realize deep copy

2022-04-29 04:26:43@huihui_ new

Overview of light copy and deep copy :

1. Shallow copy is just a layer of copy , At the deeper object level, only references are copied ;
2. Deep copy copy copy multilayer , Every level of data is copied ;

Use native JS Implement deep copy

Native JS The data types of are Value type and Reference type
about Value type (undefined;string;number;boolean;symbol;), You can easily use the assignment operation ,
But for the Reference type (Array,Object), Simple assignment operation , All you get from the assignment is the address , Commonly known as shallow copy , as follows :

const obj = {
    
    a: 13,
    b: {
     name: 'zhangsan', age: 13 },
    c: [1, 3, 4]
};
const obj2 = obj;
obj2.c[0] = 23;
console.log(obj.c[0]); //23

Yes obj2 The value modification in will also change obj The value in , Therefore, deep copy operation is required , Avoid the impact of this simple assignment operation , The code is as follows :

const obj = {
    
    a: 13,
    b: {
     name: 'zhangsan', age: 13 },
    c: [1, 3, 4]
};
function deepClone(obj = {
    }) {
    
    // Determine the value type 
    if (typeof obj !== 'object' || typeof obj == null) {
    
        return obj
    };
    // initialization result value 
    let result;
    if (obj instanceof Array) {
    
        result = [];
    } else {
    
        result = {
    };
    };
    // Perform assignment operation 
    for (let key in obj) {
    
        // Judge key Is it right? obj Attributes contained in itself , Guarantee key Not a prototype property 
        if (obj.hasOwnProperty(key)) {
    
        	// recursive 
            result[key] = deepClone(obj[key]);
        }
    };
    return result;
}
const obj3 = deepClone(obj);
obj3.c[0] = 23;
console.log(obj.c[0]);//1

Sum up , There are several considerations for implementing deep copy :

1. Judgment value type and application type 
2. Determine whether it's an array or an object 
3. recursive 

copyright notice
author[@huihui_ new],Please bring the original link to reprint, thank you.
https://en.qdmana.com/2022/117/202204270551339936.html

Random recommended