JavaScript shallow copy deep copy detailed

Source: Internet
Author: User

One, shallow copy

The most common manifestation of a shallow copy in reality is above the assignment , for example

<! DOCTYPE html>

From the example above, we modified the value of the Test2 array, and finally printed the test array, and found that the test also changed.

In fact, this is one of the lightest shallow copies, which is equivalent to test2=test this stage is to assign the storage address index in the test array to the TEST2 array, so two arrays are pointing to the same storage address .

In addition to this approach, a shallow copy can be achieved, as well as a shallow copy using slice and concat

For example: We test slice this method ( you can return the selected element as a new array from an existing array )

<script type= "Text/javascript" >    var arr=["Demo1", "Demo2", "Demo3"];    var arr2=arr.slice (0);    arr2[1]= "Test";    Console.log (arr);//["Demo1", "Demo2", "Demo3"]    console.log (ARR2);//["Demo1", "Test", "Demo3"]</script>

As we can see from the above example, a deep copy of the array is made using the slice method,

Similarly, the usage of concat is as follows ( used to concatenate two or more arrays into a new array)

<script type= "Text/javascript" >    var arr=["Demo1", "Demo2", "Demo3"];    var arr2=arr.concat ();    arr2[1]= "Test";    Console.log (arr);//["Demo1", "Demo2", "Demo3"]    console.log (ARR2);//["Demo1", "Test", "Demo3"]</script>

Why is this already a deep copy of what I call a shallow copy?

For both methods slice and concat are shallow copies, only the first layer in the array can be copied

Second, deep copy

1. Via the built-in JS function

function Deepcopy (o) {    return Json.parse (Json.stringify (o));} var a = {A:1,b:2,c:3};var b = deepcopy (a); B.A = 4;alert (A.A); 1        alert (B.A);//4, assigns a value of B.A to 4, does not affect the A object, A.A is still 1

This is a good way to understand that, for a single Object object,

First use the built-in json.stringify () function to convert it to the string "{" A ": 1," B ": 2}"

The resulting string is no longer associated with the original object, and the resulting string is converted to a new object through the Json.parse () function . {a:1, b:2}

The operation on the new object is completely independent from the old object and does not affect each other. The advantage of this method is easy to understand, using JS built-in functions to achieve, do not need too much overhead.

2. In its own way, it iterates through an array or object, returning a new array or object.

varSimplecopy =function (o) {if(o instanceof Array) {varn = [];  for(vari =0; i < o.length; ++i) {N[i]=O[i]; }        returnN; } Else if(o instanceof Object) {varn = {}         for(varIincho) {n[i]=O[i]; }        returnN; }}

3. How do I implement a copy containing an object or an array? Then it is done by a recursive copy.

varDeepcopy =function (o) {if(o instanceof Array) {varn = [];  for(vari =0; i < o.length; ++i) {N[i]=deepcopy (O[i]); }        returnN; } Else if(o instanceof Object) {varn = {}         for(varIincho) {n[i]=deepcopy (O[i]); }        returnN; } Else {        returno; }}

JavaScript shallow copy deep copy detailed

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.