A few pieces of code to help you understand shallow copy and deep copy

Shallow and deep copies of objects

The copy phenomenon will appear in objects, arrays, and functions . Here I only analyze the objects, and you can expand others by yourself (in fact, the rules are the same). When parsing object data, shallow copy and deep copy will be involved. If you don’t understand well, there will be some unexpected problems. Below I will introduce the characteristics of these two copies to help you avoid them. Possible bugs.

shallow copy

The data passed by reference : complex data, the value is the value, the address is the address, in general, the address is copied, not the value. As a result, modifying the new data will affect the data before copying. Then this phenomenon is called a shallow copy of the object.
You can understand shallow copy through the following simple example. Be sure to run the code yourself , so that what you summarize yourself really becomes your knowledge.

	var obj = {
    
    
        name:"admin"
    }
    var obj2 = obj;
    obj2.name = "root";
    console.log(obj)//{
    
    name: "root"}
    console.log(obj2)//{
    
    name: "root"}
    console.log(obj == obj2)//true

Example 2

 	var a = 10;
    var b = {
    
    
        a:20
    }
    function fn(data){
    
    
        a = 11;
        data.a = 21;
    }
    fn(b)
    console.log(a);     //11,函数中没有变量a,自动找全局a,所以修改的是全局的a
    console.log(b.a);   //21,函数中有局部变量data,不找全局,但是b是对象,对象是引用传递的数据,传参,只是简单的赋值,属于浅拷贝,所以修改新数据data,会影响老数据b

deep copy

How to make a deep copy? Parse all the data in the object and copy them one by one, avoiding passing by reference, because the data inside is passed by value.
The code example is as follows:

	var obj = {
    
    
        name:"admin",
        age:18,
        sex:0,
        like:{
    
    
            a:10,
            b:20,
            c:{
    
    
                str:"hello"
            }
        }
    }
    var obj2 = {
    
    };
    for(var i in obj){
    
    
        obj2[i] = obj[i];
    }
    obj2.name = "root";
    
    obj2.like.c.str = "world";

    console.log(obj);
    console.log(obj2);

Example 2: Realize deep copy by converting between JSON and objects

	 var obj = {
    
    
        name1:{
    
    
            name2:{
    
    
                name3:{
    
    
                    name4:"admin",
                    c:undefined,
                    b:function(){
    
    },
                    a:NaN
                }
            }
        }
    }
    var s = JSON.stringify(obj);
    console.log(s)
    var obj2 = JSON.parse(s);
    console.log(obj2.name1.name2.name3.name4);
    obj2.name1.name2.name3.name4 = "root";
    
    console.log(obj)
    console.log(obj2)
    console.log(obj === obj2)

epilogue

living comfortably without anybody's help! ! ! Remember to summarize yourself.

Guess you like

Origin blog.csdn.net/qq_38110274/article/details/103110713