I. In Javascript, if the cloned object is of the basic type, we can assign a value directly:
1 var sStr = "kingwell"; 2 var cStr = sStr; 3 alert (cStr); // output kingwell4 sStr = "abc"; 5 alert (cStr ); // output kingwell;
When a value is assigned to another variable, when the value of that variable changes, the other value will not be affected.
2. If it is not a basic type, it will be all different:
1 var random r = [,]; 2 var m = random RR; 3 alert (m); // output 1, 2, 34 random r = [,]; 5 alert (m); // The output is 3, 2,; the value is changed because m is only a reference of the branch R. If the value of the branch R changes, then m will change accordingly.
If we want to clone an array, the simplest method is as follows:
1 var branch r = [0, 1, 2, 3]; 2 var m = branch R. slice (0); 3 mirror r = [,]; 4 alert (m); // output,. Although the value in mirror R has changed, however, a new array has been created using the slice method.
We can create a function to clone all objects:
1 function clone(obj) { 2 var o; 3 if (typeof obj == "object") { 4 if (obj === null) { 5 o = null; 6 } else { 7 if (obj instanceof Array) { 8 o = []; 9 for (var i = 0, len = obj.length; i < len; i++) {10 o.push(clone(obj[i]));11 }12 } else {13 o = {};14 for (var j in obj) {15 o[j] = clone(obj[j]);16 }17 }18 }19 } else {20 o = obj;21 }22 return o;23 }
Iii. node cloning:
1 var p = document. getElementsByTagName ("p") [0]; 2 var cP = p. cloneNode (); // clone p Node 3 var cP = p. cloneNode (true); // clone the p node, perform in-depth cloning, and clone the node and its sub-content.