Says an article completely clear deep copy of JS / shallow copy

Says an article completely clear of JS deep copy and shallow copy

The audience of this article

  • The first class, business needs, the urgent need to know how deep copy JS developers object.
  • The second category, JS solid basis for hope, the future good to go good scholar interviewer before the show operation.

The first letter to readers

You only need one line of code can be achieved Black & deep copy
var copyObj = {
    name: 'ziwei',
    arr : [1,2,3]
}

var targetObj = JSON.parse(JSON.stringify(copyObj))

此时 copyObj.arr !== targetObj.arr  已经实现了深拷贝 
Do not worry go by way of doing deep copy window.JSON there are two disadvantages:
  • If you have an object in function, the function can not be copied down
  • Properties and methods can not copy the object prototype chain copyObj

Of course, you know exactly when their shortcomings, if his faults have no effect on your business needs, you can rest assured that use, a line of native code can get.

I am currently in the development business scenario, most of the really negligible 2 above drawbacks. Often need a deep copy of the object there are no functions, no need to copy the properties of its prototype chain.

The second class of readers wrote to

Now I will explain as clearly as possible the full copy of the JS objects, talk clearly copy, you need a little pre-knowledge

You need to pre-knowledge:

  • JS in understanding the difference between reference types and value types, knowing Obj stored reference only
  • Have a basic understanding of the prototype chain

All about the object copies:

  • 1. deep copy, what is a shallow copy
  • 2. deep copy and shallow copy in the business in the most common scenarios
  • 3. Copy the deep and shallow copy implementation
  • 4. Summary and Recommendations

1. deep copy, what is a shallow copy

We discuss the premise of JS objects deep copy and shallow copy

Only in the case where the target nested objects, the discussion will be based on demand, we have to deep copy or a shallow copy.

For example, such an object below

var obj1 = {
    name: 'ziwei',
    arr : [1,2,3]
}

Because, if this is similar to {name: 'ziwei'}, no nested target object, then there is no need to distinguish between shades copied. Only when there are nested object, deep and shallow copy copy only difference

Shallow copy of what it was like (we do regardless of how they implement, because the following list will tell)

After calling shallowCopy (), obj2 obj1 copy all the attributes. But obj2.arr and obj1.arr are different references point to the same memory space

 var obj2 = shallowCopy( obj1 , {})
 
 console.log( obj1 !== obj2 )                   // true    无论哪种拷贝,obj1和obj2一定都是2个不同的对象(内存空间不同)
 
 console.log( obj2.arr === obj1.arr )            // true   他们2个对象里arr的引用,指向【相同的】内存空间
    
    

So, after two obj copy, although they have the same attributes, and indeed are different objects, but they are inside the obj point to the same memory space, which we called a shallow copy

Deep copy what it was like (we do regardless of how they implement, because the following list will tell)

After calling deepCopy (), obj2 obj1 copy all attributes, and pointing to different obj1.arr obj2.arr and memory space,

In addition two copies of the same obj2 property, no other associations.

 var obj2 = deepCopy( obj1 , {})
 
 console.log( obj1 !== obj2 )                   // true    无论哪种拷贝,obj1和obj2一定都是2个不同的对象(内存空间不同)
 
 console.log( obj2.arr === obj1.arr )            // false   他们2个对象里arr的引用,指向【不同的】内存空间
    
    

So, after two obj copy, copy down the same attributes except outside, without any other association of two objects, which we called a deep copy

2. deep copy in the business in the most common scenarios

For chestnuts, business requirements are: a table showing various commodity information, click [agreed], the pop-up dialog box that can adjust the number of commodities.

In this business demand, we will use a deep copy of the object. Because the table [commodity] attributes and [adjust] commodity form of property is almost the same, we need to copy.

The following pseudo-code and images that demonstrate the use of shallow copy problem

image description

And tableArr adjustTableArr thus obtained, the internal object are the same, so there have been cases in the red marked,

When we modify the table [commodity] adjustments in the number of goods, commodities [table] change too, and this is not what we want


// 表格对象的数据结构
var tableArr = [
        {goods_name : '长袖腰背夹' , code : 'M216C239E0864' , num : '2'},
        {goods_name : '长袖腰背夹' , code : 'M216C240B0170' , num : '3'},
        {goods_name : '短塑裤' , code : 'M216D241C04106' , num : '3'},
    ]
    
var adjustTableArr = []                  // 调整表格用的数组

for (var key in tableArr) {               // 浅拷贝
    adjustTableArr[key] = tableArr[key]
}

In fact, we hope that the data in the two tables completely independent, non-interfering, only after confirming that the adjustment was to refresh the number of commodities.

In this case we can use the front of that line deep copy of Black &

var adjustTableArr = JSON.parse(JSON.stringify(tableArr))

Remember it's flaws it? Objects in the function can not be copied, the prototype chain in the property can not be copied. There would be no impact on the business, it can easily deep copy.

3. Copy the deep and shallow copy implementation

In fact, there are already JQ $ .extend () function to achieve is deep and shallow copy copy function. Interested junior partner may also look at the source.

Shallow copy

Shallow copy is relatively simple, is to use the for in loop assignment

    function shallowCopy(source, target = {}) {
        var key;
        for (key in source) {
            if (source.hasOwnProperty(key)) {        // 意思就是__proto__上面的属性,我不拷贝
                target[key] = source[key];
            }
        }
        return target;
    }
Deep copy implementation
  • Deep copy is to traverse the object is copied
  • Analyzing each item in the object data type
  • If it is not the object type, direct assignment, if the object type, call deepCopy again, recursive to assignment.
    function deepCopy(source, target = {}) {
        var key;
        for (key in source) {
            if (source.hasOwnProperty(key)) {                         // 意思就是__proto__上面的属性,我不拷贝
                if (typeof(source[key]) === "object") {               // 如果这一项是object类型,就递归调用deepCopy
                    target[key] = Array.isArray(source[key]) ? [] : {};
                    deepCopy(source[key], target[key]);
                } else {                                            // 如果不是object类型,就直接赋值拷贝
                    target[key] = source[key];
                }
            }
        }
        return target;
    }

Whether more deep and shallow copy, we have used source.hasOwnProperty (key), which means this one to determine whether its own property, if it is a copy, not the copy is not.

That __proto__ above property, I do not copy. This fact, you can according to business needs, and we decided to add to this condition

(JQ .extend of $ () on the properties will even be copied __proto__ down, but it is directly copied to the target, and not into the previous __proto__)

4. Summary and Recommendations

Although it may often use the framework provided by the api to achieve a deep copy.

The purpose of this article to share, or want to organize more clearly the meaning of shades with a copy of an article, recursive thinking, and small partners if used JSON.parse () This black technology, must be clearly written this excellent shortcomings.

Guess you like

Origin www.cnblogs.com/baimeishaoxia/p/12054563.html
Recommended