Home > Web Front-end > JS Tutorial > body text

In-depth introduction to javascript clone objects_Basic knowledge

WBOY
Release: 2016-05-16 17:48:01
Original
1046 people have browsed it

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.

Copy code 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;
}

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:
Copy code The code is as follows:

var s = JSON.stringify( obj );
var o = JSON.parse( s );
Related labels:
js
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!