js deep copy and shallow copy and the method of realizing deep copy

foreword

Why are you writing this? Because it is encountered in the project, just record it.

How to distinguish between deep copy and shallow copy

To put it simply: Assuming that B copied A, when A/B is modified, see if A/B will change. If A/B also changes, it means a shallow copy. If A/B does not change, it is a deep copy. The origin of deep copy and shallow copy lies in the reference data type and memory address. (Here you need to understand the stack and data types )
Deep copy : A memory address is opened up in the A/B computer to store the copied object.
Shallow copy : It is a reference transfer rather than a value transfer, and A and B point to the same memory address.

How to change shallow copy to deep copy

1. The easiest way: first convert to a string, and then convert to an object; JSON.parse(JSON.stringify())
2. Use recursion to copy all hierarchical attributes

Encountered scene

In vue: this.A = this.B; that is, B assigns A, and then I just want to change A; but, when I change A, B also changes; hahaha..., I used JSON.parse(JSON.stringify())

Guess you like

Origin blog.csdn.net/weixin_44897255/article/details/106721760