One: Why deep copy?
When it comes to deep copy (copying is basically a reference type of copy), you have to say stack/heap storage, JS data types, shallow copy.
1: The Stack stores basic types and occupies a fixed space. A basic type value is stored in the stack memory to hold the address of the object in the Heap memory, which is used to refer to the object.Copy the code
1: basic type ex: String, Number, Boolean, Null, Undefined. 2: reference type ex:Object, Arry, and FunctionCopy the code
Shallow copy: Changing the value of the copied object changes the value of the original copy object. Since objects are stored in heap memory, a shallow copy simply copies a pointer to the object’s value. Deep copy: Even if the property value of the copied object is changed, the original object value does not change
Let obj1={age:17, sex:"woman", address:{city:'shenzhen'}, arr:[1997," baiyu ",2000," Alibaba "]} let obj2= {age:17, sex:"woman", address:{city:'shenzhen'}, arr:[1997," baiyu ",2000," Alibaba "]} console.log("obj2:",obj2) obj2.age=34; Console. log(" after changing obj2's age value ","obj1:",obj1); Console. log(" after changing obj2's age value ","obj2:",obj2);Copy the code
Two: how to deep copy?
Function deepClone(cloneObj) {// null if(typeof cloneObj! = = "object" | | cloneobj = = null) {return cloneobj} / / initial return results let the result if (cloneobj instanceof Array) {result = []} else { Result ={}} for(let key in cloneobj){if(cloneobj.hasownProperty (key)){// Recursive call Result [key]=deepClone(cloneobj[key])}} return result} let obj1={age:17, sex:"woman", address:{"province":" province", }} let obj2=deepClone(obj1); Console. log('obj1:',obj1) console.log('obj2:',obj2) obj2.address. type =" "; Obj2. Address. City = "xi 'an"; Log (' After changing obj2's city ','obj1:',obj1) console.log(' After changing obj2's city ','obj2:',obj2) console.log(' After changing Obj2's city ','obj2:',obj2)Copy the code