Js deep and shallow copy learning (1)

1 Difference between shallow and deep copies

Copy = paste + copy, how to distinguish the depth of the copy? If I make A copy of A and give it to B, then I make changes to A. If B changes with A, it is A shallow copy, and if IT changes with A, it is A deep copy.

2 light and dark copies of things

Copy must be of a certain depth “things”, to copy, also is to copy the data type of the js data types are divided into basic data types: number, string, undefined, Boolean, null complex data types: Object (ARR,function,obj) These six data types are discussed here

3JS mechanism for data type storage

Storage of basic data types: stack memory

    let a=1
Copy the code

The procedure for stack storage is as follows: 1: create variable A and place it in the variable store of stack memory 2: create value 1 and place it in the value store of stack memory 3: “=” is assigned to make the variable and value associate

Complex data types: Stack storage

    let a={
    name:"Zhang".age:18.address:"China"
    }
Copy the code

Storage of complex data types: 1: a new block of memory is allocated to store complex type values, that is, the memory (heap) has a hexadecimal address (AAAAAAA00). 2: the key and value pairs of objects are stored in the heap one by one. 3: the address of the heap is associated with variables

4 Shallow copy

Basic data types

        let a=1;
        let b=a;
        a=2;
        console.log(a)/ / 2
        console.log(b)/ / 1
        let str="I'm Joe.";
        let newStr=str;
        str="Actually, I'm Tom."
        console.log(str);// Actually, I'm Li Si
        console.log(newStr);// I am Zhang SAN
Copy the code

I used to think that all primitive data types were deep copies, which was a mistake, but deep and shallow copies for complex data types, for primitive data types, copying a variable value is essentially copying that variable. A change in the value of one variable does not affect another variable.

Shallow copy

        var a={name:'Joe'.age:18.address:"China"}
        var b=a;
        a.age=99
        console.log(a);//{name: "zhang SAN ", age: 99, address:" China "}
        console.log(b);//{name: "zhang SAN ", age: 99, address:" China "}
        
        let arr=[1.2, {name:"Bill".age:19.address:"China"}]
        let newArr=arr;
        arr[0] =3;
        console.log(arr);//[3, 2, {name:" ",age:19,address:" "}]
        console.log(newArr);//[3, 2, {name:" ",age:19,address:" "}]
Copy the code

So copies of complex data types are usually shallow copies, meaning that the address of the value store corresponding to the variable is given to the new variable to be assigned again.

Change the content of A, and B will change.

Next time I’ll write about some common light and dark copying methods