The depth copy of JS object

Source: Internet
Author: User
Tags shallow copy hasownproperty

JS data types can be divided into (ES5, temporarily not consider ES6):

Simple data types: number, String, Undefined, Boolean

Complex data types: Object, Array

Simple data types, often assignment operations, and complex data types are reference operations.

Assignment operation we will not talk about, mainly to see the reference operation

    var arr = [n/a];    var arr2 = arr;    Arr2.push (4);    Console.log (arr);//output [1,2,3,4]

Clearly it is the operation of ARR2, why has arr changed? Because the JS storage object is a memory address, ARR2 actually stores the following: "Arr is in the in-store address";

From this we can understand that since all point to the same memory address, when we change any one, it will change.

Knowing this basic feature then we can try to understand the shallow copy and deep copy

First look at a piece of code, we'll explain the concept

    var obj ={a:1,b:2,c:[1,2]};    var shallowcopy = shallow (obj);    function Shallow (obj) {        var shallowobj = {};        for (var name in obj) {            if (Obj.hasownproperty (name)) {                Shallowobj[name] = obj[name]            }        }        return Shallowobj    }    console.log (shallowcopy);//The output is this object, we realized a simple shallow copy;

Shallow copy: Only the individual properties of the object are copied sequentially, not recursively copied, and the JS storage objects are stored addresses, so shallow copy causes obj.c and shallowcopy.c to point to the same memory address;

Deep copy: It not only copies the properties of the original object one by one, but also recursively copies the objects contained in the original object's properties to the new object, in turn, by using the method of deep copy. There is no problem with the C attribute of the above obj and shallowcopy pointing to the same object. (It's a complicated problem to post a deep copy of the code later)

Summary: It is important to note that if the object is larger and the hierarchy is more, deep replication can cause performance problems. When encountering scenarios where deep replication is required, consider whether there are other alternatives that are more commonly used in the actual referencing scenario, as well as shallow copying.

I now give a simple version of the deep copy, you can copy objects and arrays (regardless of circular reference problem, function object problem), if you want to further study, you can look at this article: http://jerryzou.com/posts/ dive-into-deep-clone-in-javascript/

Here we only understand the idea and the simple implementation, the actual project can consider using Lodash (http://lodashjs.com/docs/), or jquery Extend method can also

    function Deepclone (obj) {        var newObj = Obj.constructor = = = = Array? []:{};        if (typeof obj!== ' object ') {            return        }else{for            (var i in obj) {                if (Obj.hasownproperty (i)) {                    newobj[ I] = typeof obj[i] = = = ' object '? Deepclone (Obj[i]): Obj[i];                }}        }        Return NEWOBJ    }

The core idea is to use a recursive approach that continues until the basic data type is copied

There are a number of methods, such as the use of json.stringify for serialization, Json.parse to deserialize, to achieve "lazy version" of the deep copy ... Wait a minute

The depth copy of JS object

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.