Joke Collection Website - News headlines - Solving the problem of deep replication of objects by recursive method

Solving the problem of deep replication of objects by recursive method

First of all, for the knowledge of recursion, please refer to the link address in the previous section:

Last article: Take you to understand the recursive algorithm in LeetCode.

According to the knowledge of stack in js, we know that the basic data type of JS is value reference, and the reference type is address reference. The addresses referenced in the shallow copy are referenced by the same address. If the property value of one object is modified, another object will also be affected. In the deep copy, a new memory address will be opened to store the value of the new object. The two objects refer to different memory addresses, so modifying one object will not affect the other. For a more detailed description, please refer to the introduction about stacks.

Stack: JS Version Data Structure-Stack

The new object directly copies the reference of the object attribute of the existing object, that is, shallow copy.

For the above two copies, the name in obj is the basic data type, and the shallow copy can be assigned directly. Msg is an object, which is a complex data type. This object will open a new memory space to store the msg object, and the copied address is the same when making a shallow copy. At this time, change the value of txt in obj, and the value of txt in o will also change.

To copy an array, you can use the slicing method built into the array prototype.

Array merging is also a shallow replication.

Deep copy will copy another identical object and open a new area from heap memory to store the new object. The new object does not share memory with the original object, and the modified new object will not be changed to the original object.

Simply put: deep copy copies the spatial address of the storage object, and then copies it to the new object, so that the two objects will not directly interfere with each other.

Based on the basic data type, direct circular replication is performed. For complex data types, in order to operate circularly again, each level needs cyclic replication. We can use recursion by simply calling the for loop again on the object we encounter.

Next: the algorithm in JS. arrange

Recommended reading:

Class 1.js

2.js constructor

3. The prototype and prototype chain of objects in 3.JS

4.js.builder prototype