JavaScript – deep and shallow copy

Time:2021-5-13

As we know, JavaScript data types are divided into basic data types and reference data types.

For basic data types, there is no difference between deep copy and shallow copy. The deep copy is for reference data types.

Shallow copy:

It's just a simple copy (assignment). It won't open up a new stack. The result of copy is that two objects point to the same address. If you modify the properties of any object, the properties of the other object will also change.

```
    const = originArray = [1,2,3,4,5];
    const = originObj = {a:'a',b:'b',c:[1,2,3]};
    
    const cloneArray = originArray;
    const cloneObj = originObj;
    
    console.log(cloneArray);    //[1,2,3,4,5]
    console.log(originObj); //{a:'a',b:'b',c:Array[3]}
    
    cloneArray.push(6);
    cloneObj.a = {aa:'aa'};
    
    console.log(cloneArray);    //[1,2,3,4,5,6]
    console.log(originArray);   //[1,2,3,4,5,6]

    console.log(cloneObj);  //{a:{aa:'aa'},b:'b',c:Array[3]}
    console.log(originObj); //{a:{aa:'aa'},b:'b',c"Array[3]} 
```

Deep copy:

Open up a new stack, two objects corresponding to two different addresses, change the attributes of one object, the other object does not change.

The implementation of deep copy is as follows

1. Using parse and stringfy in JSON object
2. Using recursion to achieve each layer to re create objects and assign values

JSON.stringfy(); Converts a JavaScript value to a JSON string
JSON.parse(); Is to convert a JSON string to a JavaScript value or object
The first method is to realize:
    const originArray = [1,2,3,4,5];
    const cloneArray = JSON.parse(JSON.stringfy(originArray));
    console.log(cloneArray === originArray);//false
    
    const originObj = {a:'a',b:'b',c:[1,2,3]};
    const cloneObj = JSON.parse(JSON.stringfy(originObj));
    console.log(cloneObj === originObj);//false
    
    cloneObj.a = 'aa';
    cloneObj.c = [1,1,1];
    
    console.log(cloneObj);  //{a:'a',b:'b',c:[1,1,1]}
    console.log(originObj); //{a:'a',b:'b',c:[1,2,3]}
    
    But this method is not perfect, undefined, function, symbol will be ignored in the conversion process.
    
    If there is a function in the object, this method cannot be used for deep copy.
 
 The second method is to realize:
    function deepClone(source){
        const targetObj = source.constructor === Array ? []:{}; // Determine whether the target of the copy is an object or an array
        for(let keys in source){
            if(source.hasOwnProperty(keys)){
                If (source [keys] & & type of source [keys] = = ='object ') {// if the value is an object, recurse
                    targetObj[keys] = source[keys].constructor === Array?[]:{};
                    targetObj[keys] = deepClone(source[keys]);
                
                }Else {// if not, assign the value directly
                    targetObj[keys] = source[keys];
                }
            }
        }
        return targetObj;
    }
    
    const originObj = {
        name:'xiaochaochao',
        say:function(){
            console.log('hello world');
        }
    }
    console.log(originObj); //{name:'xiaochaochao',say:f}
    const cloneObj = deepClone(originObj);
    console.log(cloneObj);//{name:'xiaochaochao',say:f}

Copy in JavaScript (all shallow copy)

concat();   slice();
ES6 new obj. Assign()( Extension operator)

Conclusion:

1. The assignment operator makes a shallow copy
2. The four methods in JavaScript look like deep copies, but they are actually shallow copies
3. JSON. Stringfy is a deep copy
4. Recursion can achieve all deep copies

Recommended Today

What is “hybrid cloud”?

In this paper, we define the concept of “hybrid cloud”, explain four different cloud deployment models of hybrid cloud, and deeply analyze the industrial trend of hybrid cloud through a series of data and charts. 01 introduction Hybrid cloud is a computing environment that integrates multiple platforms and data centers. Generally speaking, hybrid cloud is […]