js generally has two different data types of values:
Basic types (including undefined, Null, boolean, String, Number), passed by value;
Reference types (including arrays, objects), passed by address, reference The type is the address in memory when passed by value.
Clone or copy is divided into two types:
Shallow cloning: the basic type is passed by value, and the object is still passed by reference.
Deep cloning: All elements or attributes are completely cloned and completely independent of the original reference type. That is, when the attributes of the object are modified later, the original object will not be modified.
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;
}
Another: If it is a simple array and there are no reference type values in the elements, you can directly use array.concat(); or array.slice(0); to deeply copy an array, which is simple and efficient. Array concat() and slice() will generate a new array, and the original array will not be affected. But it should be noted that you have to make sure that there are no reference type values in the elements in the copied array.
This is another deep cloning method, very simple and practical:
var s = JSON.stringify( obj );
var o = JSON.parse( s );