Deep copy and shallow copy of JavaScript

Source: Internet
Author: User
Tags shallow copy

Original

The original Book of Jane: https://www.jianshu.com/p/3d930756dd8f

Outline

Objective
1. Preliminary understanding of deep copy and shallow copy
2. The difference between a deep copy and a shallow copy
3, shallow copy of the existence of defects
4, deep copy of the implementation mode

Objective

For many first-time readers of JavaScript, the desire to copy/Copy an object is simply to use an assignment statement (=) to implement the requirement. However, such a way is not comprehensive, such a method for the simple type of data is not a problem, but if it is a complex data type such as objects, such a way of implementation will bring you an unexpected problem. So, what should we do if we can't simply use an assignment statement to copy (copy) an object? This is the meaning of deep copy and shallow copy.

1. Preliminary understanding of deep copy and shallow copy

Deep and shallow copies are only for complex objects such as Object, Array. Simply put, a shallow copy copies only the attributes of one layer of objects, while a deep copy recursively copies all levels.
For a string type, a shallow copy is a copy of the value, for the object, the shallow copy is the copy of the object address, and does not open up a new stack, that is, the result of copying two objects to the same address, modify one of the object's properties, the other object's properties will change, and the deep copy is to open up a new Two objects correspond to two different addresses, modifying the properties of an object without changing the properties of another object.

2. The difference between a deep copy and a shallow copy

Although both are copies of the content, the difference between the contents of the copy is the key to distinguishing between the two, and this difference is mainly reflected in complex objects such as object and array. The most straightforward reason is that a simple type of copy, such as a string, is a copy of the content, and there is nothing deeper than that, but for complex types such as Objcet and array, it is mainly because the copy of the object is based on the copy of the object's address rather than the overall content (the object contains the key , value).
In short: The objects after the shallow copy are actually the same object, and the objects after the deep copy are all objects that are completely unrelated except for the same contents.

3, shallow copy of the existence of defects

An example is given to illustrate the problems that can be caused by copying objects using shallow copies, thus correctly recognizing the importance of using deep and shallow copies.

var obj = {a:1, arr: [2,3]};var shallowobj = shallowcopy (obj); function shallowcopy (src) {  var dst = {};  For (var prop in Src) {    if (Src.hasownproperty (prop)) {      Dst[prop] = Src[prop];    }  }  return DST;}    /* Results in the result that        changes to the Shallowobj object also affect the original object, obj, the so-called reaching. */SHALLOWOBJ.ARR[1] = 5;obj.arr[1]   //= 5
4, deep copy of the implementation mode

Here are two ways I usually collect and commonly used deep copies of the implementation, hoping to help readers.

4.1. Solve by JSON parsing

For deep replication of pure JSON data objects, using the parse and Stringify methods of the JSON global object to achieve deep replication is also a simple flattering method. However, there are some hidden pits that can be handled correctly by using this method, with only number, String, Boolean, Array, and flat objects, which are the data structures that can be represented directly by JSON.

var test = {Person    : {        name: {First            : ' Chen ', Last            : ' KK '        },        age:12    },    interest: [' book ' Run ', ' jump ']}var result = Json.parse (json.stringify (test)) Result.interest.push (' Sing ') console.dir (test)//[' Book ', ' Run ', ' Jump ']console.dir (Result)//friend: [' book ', ' Run ', ' Jump ', ' sing ']
4.2. Solve by recursive resolution

To get a deep copy of the data in a multi-layered structure, you have to consider the way iterations are used. The following methods will need to consider deep copy objects, array data types, and continue to iterate to make deep copies of both types of data.

var China = {    Nation: ' Chinese ',    birthplaces: [' Beijing ', ' Shanghai ', ' Guangzhou '],    skincolr: ' Yellow ',    friends: [' sk ', ' ls ']}/ /deep copy, the recursive function deepcopy (o, c) {    var c = c) is required to achieve a deep copy {}    for (var i in O) {        if (typeof o[i] = = = ' object ') {            //To consider a deep copy problem            if (o[i].constructor = = = Array) {                // This is the array                c[i] = []            } else {                //This is an object                c[i] = {}            }            deepcopy (O[i], c[i])        } else {            c[i] = O [i]        }    }    Return C}var result = {    name: ' result '}result = deepcopy (China, result) console.dir (result)

  

Deep copy and shallow 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.