This article will introduce in detail the classification and implementation of js deep cloning. If you need it, you can refer to the following two types of js values:
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.
The 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:
The Code is as follows:
Var s = JSON. stringify (obj );
Var o = JSON. parse (s );