Several clone methods in Javascript

Source: Internet
Author: User

I. In JavaScript, if the cloned object is of the basic type, we can assign a value directly:

 
1 VaRSSTR = "kingwell";2 VaRCSTR =SSTR;3Alert (CSTR );//Output kingwell4SSTR = "ABC";5Alert (CSTR );//Output kingwell;

When a value is assigned to another variable, when the value of that variable changes, the other value will not be affected.

2. If it is not a basic type, it will be all different:

1 VaRRepeated r = [,];2 VaRM =Repeated RR;3Alert (m );//Output 1, 2, 34Repeated r = [,];5Alert (m );//Output 3, 2,; the value is changed, because M is only a reference of R. If the value of R is changed, M will also change accordingly.

If we want to clone an array, the simplest method is as follows:

1 VaRRepeated r = [,];2 VaRM = mirror R. Slice (0);3Repeated r = [,];4Alert (m );//Output 0, 1, 2, and 3. Although the value in reverse R has changed, a new array has been created by using the slice method.

We can create a function to clone all objects:

 1   Function  Clone (OBJ ){  2       VaR  O;  3      If ( Typeof OBJ = "object" ){  4           If (OBJ = Null  ){  5 O = Null  ;  6 } Else  {  7               If (OBJInstanceof  Array ){  8 O = [];  9                   For ( VaR I = 0, Len = obj. length; I <Len; I ++ ){  10   O. Push (clone (OBJ [I]);  11   }  12 } Else {  13 O = {};  14                   For ( VaR J In  OBJ ){  15 O [J] = Clone (OBJ [J]);  16   }  17   }  18  }  19 } Else  {  20 O = OBJ;  21   }  22       Return  O;  23 }

Iii. node cloning:

  1   var  P = document. getelementsbytagname ("p") [0 ];   2   var  CP = P. clonenode (); ///   clone a p node   3   var  CP = P. clonenode (true); ///   clone a p node, in-depth cloning: Clone the node and its sub-content.  

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.