Some methods of JS to realize deep copy

Source: Internet
Author: User
Tags shallow copy

There are two different types of values in the ECMAScript variable: the base type value and the reference type value.

Base type value: Undefined, Null, Boolean, number, String

Reference type value: Object, Array, function, etc.

Simply put, declare an array A, then assign it to B, when modifying the value of B, if the value of a does not change, it is a deep copy, if the value of a changes together, then it is a shallow copy.

Some ways to implement deep copy of an array:

1. Syntax for using ES6

var a=[1,2,3]var [... b]=a; // or b=[...a]B.push (4); Console.log (b); // 1,2,3,4Console.log (a)//

2. Using the Concat () method

var a=[1,2,3]var c=[]; var b=C.concat (a); B.push (4); Console.log (b); // 1,2,3,4Console.log (a)//

3. Using the Slice () method

var a=[1,2,3]var b=a.slice (0); B.push (4); Console.log (b); // 1,2,3,4Console.log (a)//

4. Using the Stringify and parse methods of the JSON object

var a=[1,2,3]var c=json.stringify (a); var b=Json.parse (c); B.push (4); Console.log (b) ; // 1,2,3,4Console.log (a)//

Reference Address:

Https://www.cnblogs.com/echolun/p/7889848.html

Https://www.cnblogs.com/myzy/p/8561353.html

Some methods of JS to realize deep copy

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.