Two types of data in JS and a deep copy that implements reference types

Source: Internet
Author: User
Tags shallow copy

I. Preface

We know that the data types in JS can be divided into basic types and reference types depending on how they are accessed and how they are stored.
Basic type
The base types are string, Boolean, number,undefined, Null, which are all passed by value, also known as value types.

Reference type
Reference types have objects, arrays, functions, and they are all accessed by reference.

Two. Storage mode differences

Basic types and reference types are different in how they are stored in memory, resulting in different ways of accessing them. Where the base type is stored in the stack of memory, is accessed by value, the reference type is stored in the heap of memory, and is accessed by reference. It can be as follows:

When there is

1 var n1 = ten; 2 var n2 = ten; 3 4 var arr1 = [1,2,3,4]5var arr2 = [1,2,3,4]

How it is stored in memory

The value type is the actual value of the variable that is stored directly in the stack, and the reference type simply holds the address of the variable to the heap, as can be seen, the variable N1 and N2 of the value type are 10, but in the stack it opens up two spaces for the two variables to store, The variables of the reference type ARR1 and arr2 are the same, but only a piece of memory is created in the heap to store, and the two variables are stored in the stack to point to the address in the heap, both of which point to the same piece of address in the heap.

Three. Copy Differences

It is because of the differences in the way they are stored that they differ in their copy. First, let's look at two pieces of code:

1 var n1 = ten; 2 // Copy the N1 to N2 3 var n2 = N1; 4 5 n1 =N; 6 Console.log (N1); 7 Console.log (N2);

Define the variable n1=10 first, then copy the N1 to N2, then change the value of N1 to 12, print the values of N1 and N2 respectively, and print the result as follows:

As we can see from the results, N1 becomes 12, but N2 is not affected, it is still 10.

Look at another piece of code:

1 var arr1 = [1,2,3,4]2// copy arr1 to arr23var arr2 =  arr1; 4 // add an element to the tail of arr1 5 5 Arr1.push (5); 6 7 Console.log (arr1); 8 Console.log (ARR2);

Define the array arr1, then copy the arr1 to ARR2, and then append an element to the end of the arr1 to print the values of arr1 and arr2 respectively, printing the result:


From the results we can see: We first copied the arr1 to arr2, but when we changed the ARR1, ARR2 changed along with it. This confirms that, arr1 and arr2 are actually pointing to the same address in memory, when the arr1 changes, actually will point to the memory address of the data changes, and ARR2 also point to the address, so ARR2 will follow the change.

The above code in the ARR2=ARR1, is what we commonly known as shallow copy, shallow copy is only a copy of the variable name, its storage in memory is not copied, pointing to the same piece of memory address, which is caused by a change in another also followed the change, which in the daily development is not what we want.

So how do you make a real copy?

Four. Achieve deep copy

The real copy, that is, after the copy, arr1 and arr2 Point is no longer the same memory address, but points to their respective addresses, so that changes will not occur at the same time changes, this is a deep copy.

Below we encapsulate a deep copy function to implement a deep copy of the reference type:

1Parameter P is the original object2 //The parameter C is the type of the original object, the Wakahara object is an array, the incoming C is [], the Wakahara object is the object passed in C as {}, or it does not pass the default to {}3 functiondeepcopy (p,c) {4 varc = C | | {};5  for(varIinchp) {6     if(typeofP[i] = = = "Object"){7C[i] = (P[i].constructor = = = = Array)?[]:{};8       deepcopy (P[i],c[i])9}Else{TenC[i] =P[i] One    } A     } -     returnC; -}
Five. Testing
1 //parameter P is the original object2 //The parameter C is the type of the original object, the Wakahara object is an array, the incoming C is [], the Wakahara object is the object passed in C as {}, or it does not pass the default to {}3 functiondeepcopy (p,c) {4 varc = C | | {};5  for(varIinchp) {6     if(typeofP[i] = = = "Object"){7C[i] = (P[i].constructor = = = = Array)?[]:{};8        deepcopy (P[i],c[i])9}Else{TenC[i] =P[i] One       } A     } -     returnC; - } the  - //defining an array arr1 - varARR1 = [1,2,3,4] - //Copy the arr1 to ARR2 + varARR2 =deepcopy (arr1,[]); - //add an element to the tail of arr1 5 +Arr1.push (5); AConsole.log (' arr1: ', arr1); atConsole.log (' arr2: ', arr2);

Test results:

As can be seen in the results, arr1 changes did not cause arr2 changes, and the real copy was realized.

Finish

Two types of data in JS and a deep copy that implements reference types

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.