Deep copy and shallow copy of about js

First, the concept and principle analysis

Simply put, a shallow copy is shallow copy, one copy only, for deep-seated object is a copy of his references; deep deep copy is a copy of each layer will have to copy the object. Shallow copy of the object is not guaranteed and do not associate with the original object, but a deep copy of an object absolutely nothing to do with the original object, the original object change will not have any impact on a deep copy of the object.

Read many articles, some articles say shallow copy is a copy of an object reference, common reference address a heap with the original copy of the object through the object shallow, so shallow copy of the new object association can not solve the problem with the original object, and deep copy is complete generate a new object, the object is not associated with the original, the new object change will not affect the original object. I think this argument is not comprehensive enough, because shallow copy may also make a new object with the original object disassociated, as long as the original object only one layer.

In short depth of copies of the ultimate goal is to copy the original object with a new object-independent, to be specific when to use shallow copy, when to use a deep copy needs to be used flexibly according to the actual situation.

Second, to achieve deep and shallow copy copy method

(A) a method shallow copy

1.Object.assign method

For only one layer of the object, that the object attribute values ​​are all the basic data types, data types do not contain references using Object.assign shallow copy of it

As can be seen by the debug console change a value of this object obj1, the value of a obj2 not changed

If obj1 is a two objects do, that there are target objects

At this time we can see that with the change of obj1, obj2 also changed, use Object.assign shallow copy to die

2.Array.from method

For an array of only one layer, using Array.from shallow copy of the line

If an array of objects, using Array.from would not, in the following example, an array of a change affects both a and b

(B) deep copy method

1. recursive traversal

Recursion is a method for traversing a deep copy of an object that is no matter how many levels, both for him to traverse, he attributes of each level are re-copied to the properties of the new object, the new object will not produce such longer the impact of the original object.

In the above example, object OBJ1 is a multilayer, we use a recursive traversal of the deep copy to his obj2, then changing the value OBJ1, no impact on obj2

2.JSON.stringify和JSON.parse

利用JSON.stringify和JSON.parse也可以实现对象的深拷贝

b = JSON.stringify(a);
b = JSON.parse(b);

但是要注意一点,这种方法只适合对象的属性当中没有function或 RegExp 这些值,因为字符串没法对这种类型进行解析

发布了27 篇原创文章 · 获赞 6 · 访问量 2万+

Guess you like

Origin blog.csdn.net/github_37673306/article/details/93862521