A deep copy of JavaScript

Source: Internet
Author: User
Tags shallow copy hasownproperty

Shallow copy of an array

If it is an array, we can use some of the array's methods such as: Slice, CONCAT returns a new array of attributes to achieve the copy. Like what:

 var  arr = [ "  old   ",  1 , true , null   var  new_arr =   Arr.concat ()  ; new_arr[ 0 ] =  " new  "  ;console.log (arr)  Span style= "COLOR: #008000" >//  ["old", 1, true, null, undefined]  Console.log (New_arr) //  ["New", 1, true, NULL, Undefined]   
 var  arr = [ "  old   ",  1 , true , null   var  new_arr =   Arr.slice ()  ; new_arr[ 0 ] =  " new  "  ;console.log (arr)  Span style= "COLOR: #008000" >//  ["old", 1, true, null, undefined]  Console.log (New_arr) //  ["New", 1, true, NULL, Undefined]   

The concat () method is used to concatenate two or more arrays. The method does not alter the existing array, but simply returns a copy of the concatenated array, which returns a new array. Syntax: Arrayobject.concat (Arrayx,......, Arrayx), the array is generated by adding all the Arrayx parameters to the Arrayobject. If the argument for the concat () operation is an array, then the element in the array is added, not the array .

The Slice () method returns the selected element from an existing array. Syntax: Arrayobject.slice (start,end), returns a new array containing the elements from start to end (excluding the element) in Arrayobject. Note that the method does not modify the array, but instead returns a subarray. If you want to delete an element from an array, you should use Method Array.splice ().

Note: 1, you can use negative values to select elements from the end of the array. 2. If end is not specified, then the slice () method selects all elements from start to the end of the array.

However, if an array is nested with an object or array, for example:

vararr = [{old:' Old'}, [' Old']];varNew_arr =Arr.concat (); arr[0].old ='New'; arr[1][0] ='New'; Console.log (arr)//[{old: ' new '}, [' New ']]Console.log (New_arr)//[{old: ' new '}, [' New ']]

We will find that both the new array and the old array have changed, that is to say, using the concat method, cloning is not exhaustive. Here you can contact the previously written value of the pass-through and reference-pass, stack-memory and heap-memory problems: If the array element is a primitive type, it will copy one copy, do not affect each other, and if it is an object or an array, it will only copy objects and arrays of references, This will change both the old and new arrays .

we refer to this copy-referenced copy method as a shallow copy , which corresponds to a deep copy, a deep copy is a complete copy of an object, even if nested objects, the two are separated from each other, modify the properties of an object, will not affect the other. So we can see that using concat and slice is a shallow copy.

Deep copy of array

So how do you make a deep copy of an array? Here's a tip that applies not only to arrays but also to objects! That is:

vararr = [' Old',1,true, ['Old1','Old2'], {old:1}]var New_arr = Json.parse (json.stringify (arr)); new_arr[3][0] ='New'; new_arr[4].old =2; Console.log (Arr,new_arr);

is a simple and rude good way, is that there is a problem, can not copy the function, we do an experiment:

The realization of shallow copy

The above three methods concat, slice, json.stringify is a skill class, can be based on the actual project situation to choose to use, next we think about how to implement an object or an array of shallow copies.

Think about it, it seems very simple, traverse the object, and then put the property and property values in a new object is not good ~ Ah, it is so simple, pay attention to a few small points on it:

varShallowcopy =function (obj) {//Copy objects only    if(typeofObj!=='Object')return; //determines whether to create a new array or an object based on the type of obj    varNEWOBJ = obj instanceof Array? [] : {}; //iterates over obj and determines that it is a property of obj to copy     for(varKeyinchobj) {        if(Obj.hasownproperty (key)) {Newobj[key]=Obj[key]; }    }    returnNEWOBJ;}vararr = [{old:" Old"},[" Old"]];varNewarr =shallowcopy (arr); Console.log (newarr);//[{old: ' new '},[' old ' ]newarr[0].old ='New'; Console.log (Arr,newarr);//[{old: ' new '},[' old '], [{old: ' new '},[' old ' ]

Implementation of deep Copy

So how do you make a deep copy? It's easy to say, we are copying the type of property values, if it is an object, we recursively call deep copy function is not good ~

varDeepcopy =function (obj) {//Copy objects only    if(typeofObj!=='Object')return; //determines whether to create a new array or an object based on the type of obj    varNEWOBJ = obj instanceof Array? [] : {}; //iterates over obj and determines that it is a property of obj to copy     for(varKeyinchobj) {        if(Obj.hasownproperty (key)) {/*if (typeof Obj[key] = = = "Object") {Newobj[key] = deepcopy (Obj[key]); }else{Newobj[key] = Obj[key]; }*/Newobj[key] = typeof Obj[key] = = = "Object"? deepcopy (Obj[key]): Obj[key] }} returnNEWOBJ;}vararr = [{old:" Old"},[" Old"]];varNewarr =deepcopy (arr); Console.log (newarr);//[{old: ' new '},[' new ']newarr[0].old ='New'; newarr[1][0] ='New'; Console.log (Arr,newarr);//[{old: ' old '},[' old ']],[{old: ' New '},[' new ']

Performance issues

Although using a deep copy will completely clone a new object without any side effects, the deep copy is not as good as a shallow copy because it uses recursion, in development, or as a practical choice.

A deep copy of JavaScript

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.