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

E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

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: and provide relevant evidence. A staff member will contact you within 5 working days.