A shallow copy is only a copy of one layer (the underlying data type), and a copy of the first type (the compound data type) at the deeper object level: a shallow copy
Requirement: Copy obj to Olet obj ={id:1.name:"and" , msg{ age: 18}};leto ={}; Method 1: use traversal to achieve shallow copyfor(let k inObj) {note: k stands for attribute name obj[k] stands for attribute value o[k] = obj[k]; } o.msg.age =20 ; // Modify one of themPrint obj.msg.age and O.MSG.age? The result is20Note :(compound data type) just copy (address in the stack) to the new object o, pointing to the same heap of data, each modification has an effect.Copy the code
Method 2: It is recommended to use the new method in ES6 to shallow copy syntax:Object.assign(to whom the shallow copy will be assigned)Object. Assign (o,obj) print obj.msg.age and O.MSG.age? The result is the same as aboveCopy the code
Shallow copies (compound data types) are shown below:
Deep copy copies multiple layers of data at each level
Popular: deep copy (compound data type), in the heap to create their own memory space copy (compound data type), modify each other does not affect each other
Requirement: Copy obj to Olet obj ={id:1.name:"and" , msg{ age: 18}, arr: ['red'.'pink']};
letO ={} Funtion deepCopy (new , old){
for(let k inOld) {k stands for attribute name old[k] stands for attribute valueletitem =old[k]; Note: Store attribute values for determining types1.Determine what type the data belongs toif(item instanceof Array) {2.Determine if the value is an array (compound data type)new[k] = [] ; Note: is an array type, the value first defines an empty array, convenient data deepCopy (new[k], item) deep copy old value to new value (o)}else if( item instanceof Object) {3.Determine if the value is an object (composite data type)new[k] = {} ;
deepCopy ( new[k] , item)
}else{
4.Belong to (base data type)new[k] = item;
}
}
}
deepCopy (o , obj)
5.Change o.MSG. Age = in the new object20Print the obj.msg.age and O.MSG. age results20.18Description: deep copy (compound data type), the new object (O) in the heap memory to open up their own space to store copied data, each modification does not affect each other.Copy the code
Shallow copy multilayer (compound data type) as shown below:
Conclusion:
- Shallow copy:
Copies of addresses (compound data types) refer to the same heap, modifying each other and affecting each other.
- Deep copy
Copy (compound data type), create its own memory space in the heap, store the copied “compound data type”, modify each other does not affect each other.
- There are two forms of variable value transfer in JS:
(1) Value transfer: Modification of each other has no effect (basic data type)
(2) Reference-passing: Changes to each other have an impact (compound data types), also known as shared references
Note: All variable names are stacks