First, shallow cloning
1. Cloning of basic data type (assigned value)
var a = 1; var b =//1//1a = 2//2 // 1
When you assign a value to another variable, the value of that variable is not affected when it is changed.
2. Array cloning
If we take the basic data type (Assignment) for cloning, the case is as follows:
var arr1 = [1, 2, 3]; var =//arr2//Arr1.push (4// ) 1,2,3,4 // 1,2,3,4
Because arr2 refers to arr1, they point to the same address in memory, so arr1 changes can also lead to arr2 changes! What if you want to implement a shallow clone of an array?
We used the slice method of the array to clone the code as follows:
var arr1 = [1, 2, 3]; var =//arr2//Arr1.push (4// ) 1,2,3,4 // the
second, deep cloning
functionClone (obj) {varO, I, J, K; if(typeof(obj)! = "Object" | | obj = = =NULL) { returnobj; } if(objinstanceof(Array)) {o= []; I= 0; J=obj.length; for(; i < J; i++) { if(typeof(Obj[i]) = = "Object" && obj[i]! =NULL) {O[i]=Arguments.callee (Obj[i]); } Else{O[i]=Obj[i]; } } } Else{o= {}; for(Iinchobj) { if(typeof(Obj[i]) = = "Object" && obj[i]! =NULL) {O[i]=Arguments.callee (Obj[i]); } Else{O[i]=Obj[i]; } } } returno;}
JavaScript Shallow clone and deep clone