This article brings you a brief analysis of deep copy and shallow copy in js. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
Regarding deep copy and shallow copy, they are actually two relatively basic concepts, but I still want to sort them out because there are many small details in them that are still very interesting.
Deep copy and shallow copy are two terms that everyone often hears. What is the difference between them?
Let’s first look at what shallow copy is.
var obj1 = { a: 1, b: 2 }; var obj2 = obj1; obj2.a = 3; console.log(obj1); // { a: 3, b: 2 } console.log(obj2); // { a: 3, b: 2 }
This is the simplest example of shallow copy. I assigned obj1 to obj2 and changed an attribute value in obj2. The corresponding attribute value in obj1 also changed accordingly. Why is this?
Because shallow copy is actually just a copy of the reference, both still point to the same address in memory. In short, obj1 and obj2 actually point to the same object. For example, it's like a room whose house number 1 has been replaced by house number 2, but this room is still the same room.
Thendeep copy means that the two point to different memory addresses, which is a true copy. Take the room above as an example, that is, you really opened a new room, not just changed the house number.
Object.assign() is a method we often use. In fact, this method is shallow copy. But it has something special, that is, it can handle deep copies of the first layer.
var obj1 = { a: 1, b: { c: 2 } }; var obj2 = Object.assign({}, obj1); obj2.a = 3; obj2.b.c = 3; console.log(obj1); // { a: 1, b: { c: 3 } } console.log(obj2); // { a: 3, b: { c: 3 } }
Looking at the above example, the value of attribute a has not changed, but the value of c in attribute b has changed.
This is the most commonly used way to implement deep copy, just look at the example:
var obj1 = { a: { b: 1 } }; var obj2 = JSON.parse(JSON.stringify(obj1));
This kind The method is simple and easy to use, but it has a slight flaw in that it discards the object's constructor. That is to say, after deep copying, no matter what the original constructor of the object is, it will become Object after deep copying.
And the only objects that this method can correctly handle are Number, String, Boolean, and Array, that is, those data structures that can be directly represented by JSON. RegExp objects or functions cannot be deep copied in this way.
This is the method I currently use. It only takes one line var obj2 = _.cloneDeep(obj1)
to achieve it. Moreover, lodash is a very powerful library and the methods provided are reliable and simple. It is really a must-have for lazy people.
The above is the detailed content of A brief analysis of deep copy and shallow copy in js. For more information, please follow other related articles on the PHP Chinese website!