Let’s start with shallow copy:

This is a shallow copy

But there is a problem with shallow copy. We have copied a reference type from shallow copy above. What if we change obj?

We can see that by shallow copying a reference type, if we change obj, we end up changing B, because when we copy it, we’re just copying the reference address to B, which means that B and obj refer to the same object

So we’re going to have to improve our code by taking the elements out of OBJ and handing them to B

That would be the perfect solution hahaha

But we, as good programmers, are going to find the problem, and then the next question is, what if OBj contains a C object, and we change C

When we modify the object obj inside of c, b, c also follow changes in reason is that b copy of c is also a reference type, which is just a copy of the address, and there is a problem, is that we don’t know the number of layers in the obj, could also contains a reference type c1, And we don’t know whether the reference type is an object or an array, so we have to solve this problem, which is called deep copy.

We can start with a simple way to implement deep copy

Let’s start with the code we need to copyJSON.stringifyConvert to character, and then reuseJSON.parseThe character is rotated back to the object to complete the copy

But some interviewers will ask you, can you do it recursively? The answer is of course

We use recursion for deep copy

What’s the idea of recursion? So let’s analyze it

  • We must define a method that eventually returns a deep copy of the data
  • To return a data, we first define a data, but is the data an object or an array? So you have to decide, if the data you’re copying is an array, you define an array, if it’s an object, you define an object
  • Method inside how copy ah? It’s the same utilizationfor inThe loop, inside the loop, needs to decide, if it’s a simple type, copy it directly, if it’s a reference type, it needs to fetch the value from the reference type at a time

Let’s deal with the code based on the above logic

At this point a deep copy is complete