Today, let's learn about deep copy and shallow copy in JS.
First of all, we have to know, what is a deep copy and what is a shallow copy?
There are actually two types of variables in JS. 1. Basic type 2. Reference type
In basic types, such as var str="app"; var num=1;
Reference type: var obj={type:1}; var arr=[1,2,3];
It can be seen that primitive types are value types, and reference types are regular objects and arrays.
1. Basic type
var str="string";
var num=str;
var str=666;
console.log(str,num)//666 "string"
It can be seen here that after str is reassigned, num is not assigned to 666, indicating that the references of str and num point to different data.
2. Reference type
var obj={type:1};
var arr=obj;
obj.type=666;
console.log(obj,arr) // type:666 type:666
It can be seen here that after we reassign obj.type, the data of arr has also changed, indicating that they refer to the same data source.
For reference type data, we may modify the data in our usual work, which will cause other reference values to change. This is of course not the result we want, and bugs are prone to occur. We need to copy the source data for assignment. Modification, so this brings us to our deep copy, shallow copy.