Use the JSON method to make deep copies of something you should know!

Source: Internet
Author: User

Before writing JS More of the time also written deep copy, shallow copy, inherit what, there are custom monitoring events. But it took a long time to forget.

The most recent deep copy used in the project is B = Json.parse (Json.stringify (a)), did not delve into the principle, and did not consider hundred percent correctness. It's just a lot of mistakes.

But when someone in the group asked how to make a deep copy, I threw out this simple method. There is a great God out there to say that this is not true. Instant Meng, after the great God guidance and their popularity. Finally found the pit, a burst of sweating!

The pit point is that if you want a deep copy of the object property value to be undefined or function, it will be filtered out!

1.JSON does not support nan,infinity, even accurate floating-point numbers, let alone circular references and function.

2. Serialization is serialization, deserialization is deserialization, do not misuse.

3. b = JSON.parse( JSON.stringify(a) )  Limitations: Unable to copy function; The prototype chain is gone, the object is objects, the class that belongs to is gone. But he is simple, most of the time can fully meet the demand!

By the way, a good deep copy function is attached. 

var a={
M:undefined,
B:2,
c:[1,2,3],
d:[1,[2,3],4],
E:null,
F:function () {
Console.log (' 11 ')
}
}
function Deepcopy (p,c) {
var i;
c = c| | {};
For (I in P) {
if (P.hasownproperty (i)) {
if (typeof (P[i]) = = = = "Object") {
C[i] = Array.isarray (P[i])? []:{};
Deepcopy (P[i],c[i]);
}else{
C[i] = P[i];
}
}
}
return C;
}
var b=deepcopy (B,a)
Console.log (b)

Printing results:

  

Use the JSON method to make deep copies of something you should know!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.