What is shallow copy and deep copy
1. Variable storage mechanism
- Memory is divided into stack memory and heap memory. Simple data types are stored in stack memory, complex data type references are stored in stack memory, and actual values are stored in heap memory, as shown in the following diagram
Shallow copy & deep copy
- Shallow copy: Only references are copied and no new space is created in the heap to store copy objects, resulting in two references pointing to one memory space, one affected by the other.
- Deep copy: Copy references, create new storage space in the heap to store copied objects, original objects and copied objects do not affect each other.
Second, concrete implementation
1. The shallow copy
- One ️ for in, 2️ object. assign(), 3️ = value
(1)
(2) the Object. The assign ()
(3) = assignment
let obj = {};
let obj1 = obj;
Copy the code
2. Deep copy
- One ️ jSON. parse&json. stringify, 2️ one, 3️ one cloneDeep(value)
(1) JSON. Parse&JSON. Stringify
- Json. parse: Parse JSON from a string (key-value pairs)
- Json. stringify: Parse a string from a JSON object
- Problem: The prototype chain of the original Object is missing, pointing to Object
(2) Recursion
(3) the Lodash
_.cloneDeep(obj)