Javascript deep copy

Source: Internet
Author: User

It seems that there are two other similar functions in my blog, but they have been around for a long time. With the improvement of my technology, better functions have been created. When I suddenly asked about my previous functions, I also paused and thought, it's really bad! I always like to share the best things with everyone. Forget it before.

Let's take a look at the defects of the shortest replication. I don't know how many people have done it?

      var oOriginal = {        memNum: 1,                                      // number        memStr: "I am a string",                      // string        memObj: {          test1: "Old value"                              // we’ll test        },        memArr: [                                         // array           "a string",                                       // string member of array          {                                                   // object member of array            test2: "Try changing me"                 // we'll test          }        ]      };

This is a complex object that contains objects and arrays. Let's take a look at the complexity of the famous inheritance function of Prototype. It is hard to say that it is inheritance, and jQuery does not.

      var extend = function(result, source) {        for (var key in source)          result[key] = source[key];        return result;      }

Test procedure:

Var oCopy = extend ({}, oOriginal); // copy oCopy. memObj. test1 = "New value"; // if a problem occurs, alert (oOriginal. memObj. test1); // The result copy is modified with oCopy. memArr [1]. test2 = "I am changed"; alert (oOriginal. memArr [1]. test2); // same trick

<Br/> <! Doctype html> <br/> <ptml lang = "en"> <br/> <pead> <br/> <meta charset = "UTF-8"/> <br/> <meta content = "IE = 8" http-equiv = "X-UA-Compatible"/> <br/> <title> javascript deep copy by situ zhengmei </title> </ p> <script type = "text/javascript"> <br/> var oOriginal ={< br/> memNum: 1, // number <br/> memStr: "I am a string", // string <br/> memObj :{< br/> test1: "Old value" // we'll test <br/>}, <br/> memArr: [// array <br/> "a string ", // string member of array <br/> {// object member of array <br/> test2: "Try changing me" // we'll test <br/>}< br/>] <br/>}; <br/> var extend = function (result, source) {<br/> for (var key in source) <br/> result [key] = source [key]; <br/> return result; <br/>}< br/> var oCopy = extend ({}, oOriginal); // copy <br/> oCopy. memObj. test1 = "New value"; // if a problem occurs, it is reflected to the original object. <br/> alert (oOriginal. memObj. test1); // The result copy is modified together with the original one <br/> oCopy. memArr [1]. test2 = "I am changed"; <br/> alert (oOriginal. memArr [1]. test2 ); // The same trick was found. <br/> </script> </p> </pead> <br/> <body> <br/> <p> javascript depth copy by situ zhengmei </p> <br/> </body> <br/> </ptml> <br/>

Run code

It seems that if you do not want to modify the original object, we need to specially process the object and array. To process them, we must recognize them. See the following functions:

/*** Type identification-By situ zhengmei: cheng (MIT Licensed) * http://www.cnblogs.com/rubylouvre/archive/2010/01/20/1652646.html */var is = function (obj, type) {var toString = Object. prototype. toString, undefined; return (type = "Null" & obj = null) | (type = "Undefined" & obj = undefined) | toString. call (obj ). slice (8,-1) === type ;};

The above function is used for type recognition. typeof is unreliable. Array will return "object", and instanceof will not work. It cannot determine the Array instance of another document object. Although the use of Object. prototype. toString. call is not perfect, the duck type can be easily counterfeited, but it is always more reliable than before.

Next, we officially enter the topic. Our deep copy function will specially process key-value pairs of objects and arrays. For them, the program will first create a new object and array for the target object, then copy them one by one. We can see that it does not use hasOwnProperty, in other words, even the properties that can be traversed in the prototype are all given to it. For arrays, we do not need to loop for (,). It can only loop through the elements in parentheses, and cannot loop through other attributes attached to the array. Therefore, we still need to... in this slow method. Since deep copy detects all attributes and creates new objects in the middle, it is a very heavy method. Use it unless necessary.

/*** Type identification-By situ Zheng MEI: cheng (MIT Licensed) * http://www.cnblogs.com/rubylouvre/archive/2010/03/26/1696600.html */dom. deepCopy = function (result, source) {for (var key in source) {var copy = source [key]; if (source = copy) continue; // window. window === window, will be in an endless loop, you need to process if (dom. is (copy, "Object") {result [key] = arguments. callee (result [key] | |{}, copy);} else if (dom. is (copy, "Array") {result [key] = arguments. callee (result [key] | [], copy) ;}else {result [key] = copy ;}} return result ;};

<Br/> <! Doctype html> <br/> <ptml lang = "en"> <br/> <pead> <br/> <meta charset = "UTF-8"/> <br/> <meta content = "IE = 8" http-equiv = "X-UA-Compatible"/> <br/> <title> javascript deep copy by situ zhengmei </title> </ p> <script type = "text/javascript"> <br/> var oOriginal ={< br/> memNum: 1, // number <br/> memStr: "I am a string", // string <br/> memObj :{< br/> test1: "Old value" // we'll test <br/>}, <br/> memArr: [// array <br/> "a string ", // string member of array <br/> {// object member of array <br/> test2: "Try changing me" // we'll test <br/>}< br/>] <br/>}; <br/> dom = {}; <br/> dom. is = function (obj, type) {<br/> var toString = Object. prototype. toString, undefined; <br/> return (type = "Null" & obj = null) | <br/> (type = "Undefined" & obj = undefined) | <br/> toString. call (obj ). slice (8,-1) ==== type; <br/>}; </p> <p> dom. deepCopy = function (result, source) {<br/> for (var key in source) {<br/> var copy = source [key]; <br/> if (source = copy) continue; // such as window. window = window, will be in an endless loop <br/> if (dom. is (copy, "Object") {<br/> result [key] = arguments. callee (result [key] | |{}, copy); <br/>} else if (dom. is (copy, "Array") {<br/> result [key] = arguments. callee (result [key] | [], copy); <br/>} else {<br/> result [key] = copy; <br/>}< br/> return result; <br/>}; <br/> var oCopy = dom. deepCopy ({}, oOriginal); // copy <br/> oCopy. memObj. test1 = "New value"; // if a problem occurs, it is reflected to the original object. <br/> alert (oOriginal. memObj. test1); // The result copy is modified together with the original one <br/> oCopy. memArr [1]. test2 = "I am changed"; <br/> alert (oOriginal. memArr [1]. test2 ); // The same trick was found. <br/> </script> </p> </pead> <br/> <body> <br/> <p> javascript depth copy by situ zhengmei </p> <br/> </body> <br/> </ptml> <br/>

Run code

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.