JavaScript Shallow clone and deep clone

Source: Internet
Author: User

First, shallow cloning

1. Cloning of basic data type (assigned value)

var a = 1; var b =//1//1a = 2//2 // 1

When you assign a value to another variable, the value of that variable is not affected when it is changed.

2. Array cloning

If we take the basic data type (Assignment) for cloning, the case is as follows:

var arr1 = [1, 2, 3]; var =//arr2//Arr1.push (4// ) 1,2,3,4 // 1,2,3,4

Because arr2 refers to arr1, they point to the same address in memory, so arr1 changes can also lead to arr2 changes! What if you want to implement a shallow clone of an array?

We used the slice method of the array to clone the code as follows:

var arr1 = [1, 2, 3]; var =//arr2//Arr1.push (4// ) 1,2,3,4 //  the

second, deep cloning  

functionClone (obj) {varO, I, J, K; if(typeof(obj)! = "Object" | | obj = = =NULL) {        returnobj; }    if(objinstanceof(Array)) {o= []; I= 0; J=obj.length;  for(; i < J; i++) {            if(typeof(Obj[i]) = = "Object" && obj[i]! =NULL) {O[i]=Arguments.callee (Obj[i]); } Else{O[i]=Obj[i]; }        }    } Else{o= {};  for(Iinchobj) {            if(typeof(Obj[i]) = = "Object" && obj[i]! =NULL) {O[i]=Arguments.callee (Obj[i]); } Else{O[i]=Obj[i]; }        }    }    returno;} 

JavaScript Shallow clone and deep clone

Related Article

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.