Js generally has two different data types:
Basic type (including undefined, Null, boolean, String, Number), passed by value;
The reference type (including arrays and objects) is passed by address. The reference type is the address in the memory when the value is passed.
There are two types of clone or copy:
Simple clone: the basic type is value transfer, and the object is still passed as a reference.
Deep cloning: All elements or attributes are completely cloned and the original reference type is completely independent. That is, the original object will not be modified when the attributes of the object are modified later.
Copy codeThe Code is as follows:
Function cloneObject (obj ){
Var o = obj. constructor === Array? []: {};
For (var I in obj ){
If (obj. hasOwnProperty (I )){
O [I] = typeof obj [I] = "object "? CloneObject (obj [I]): obj [I];
}
}
Return o;
}
In addition, for a simple array, the element does not reference the type value, you can directly use array. concat (); or array. slice (0); To copy an array in depth, which is simple and efficient. The concat () and slice () arrays will generate a new array, and the original array will not be affected. However, make sure that the elements in the copied array do not contain reference values.
This is another method of deep cloning, which is very simple and practical:
Copy codeThe Code is as follows:
Var s = JSON. stringify (obj );
Var o = JSON. parse (s );