Deep copy and shallow copy in JS

Source: Internet
Author: User

First, the preliminary distinction between deep copy and shallow copy

JS has a deep copy and a shallow copy of the said. What is a deep copy and what is a shallow copy, simply put it: suppose B replicates a, and when you change a, see if B changes. If b also follows the change, it is a shallow copy. If B does not change, it is a deep copy.

Second, in-depth understanding

There are basic data types and reference data types in JS.

Data type: number,string, Boolean, null, undefined five classes.

Reference data types (object class), unordered objects, arrays [All-in-a-kind], and functions.

1, the basic data type--can be considered a deep copy ( both the name and value are present in the stack memory )

Let A=1

When B=a is copied, a new memory is opened in the stack memory:

So when you modify the a=2 at this time, it will not affect B, it can be said to be a deep copy, but not a deep copy in strict sense.

2, the Reference data type (the name exists in the stack memory, the value exists in the heap memory, but the stack memory will provide a reference to the address of the value in the heap memory )

Let A= [0,1,2,3,4]

When B=a makes a copy, it actually replicates the reference address of a, not the value inside the heap.

When the data is modified when a[0]=1, because a and bar point to the same address, so B is also affected, this is a shallow copy.

Third, how to achieve a shallow copy into a deep copy

1. Recursive method

Recursively copies the properties of all levels.

functionDeepclone (obj) {let Objclone= Array.isarray (obj)?[]:{}; if(obj &&typeofobj=== "Object"){         for(Keyinchobj) {            if(Obj.hasownproperty (key)) {//determines whether the OJB child element is an object, and if so, recursively replicates                if(obj[key]&&typeofObj[key] = = = "Object") {Objclone[key]=Deepclone (Obj[key]); }Else{                    //if not, simply copyObjclone[key] =Obj[key]; }            }        }    }    returnObjclone;} Let a=[1,2,3,4], b=Deepclone (a); a[0]=2; Console.log (A, b);

The console prints out:

B is not affected by a, so it is a deep copy.

But:

Copy not completely Ah, the B object's first-level properties are not affected, but the level two attribute is still not able to copy the success, still can not escape the control of a, that slice is not really a deep copy.

2. Parse and stringify of JSON object

function Deepclone (obj) {    = json.stringify (obj),        = json.parse (_obj);     return Objclone}    Let a=[0,1,[2,3],4],    b=deepclone (a); a[0]=1; a[2][0]=1; Console.log (A, b);

B is unaffected by a, and realizes a deep copy.

3, in addition to the above two methods, we can also borrow the Extend method of JQ.

deep Copy, deep copy for True, and false for shallow copy

Target The object type is the target object, and the member properties of other objects are appended to it.

Object1 objectn Optional. Object type the first and nth merged objects.

Let a=[0,1,[2,3],4],    b=$.extend (true, [],a); a[0]=1; a[2][0]=1; Console.log (A, b);

Implement a deep copy.

Deep copy and shallow copy in JS

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.