Home > Article > Web Front-end > How to implement deep cloning in javascript
How to implement deep cloning in javascript: 1. Use the "..." extension operator to deep clone one layer, but the second layer reference still points to the original location; 2. Use JSON to achieve multi-layer Deep cloning, but functions cannot be copied and cannot be applied to all scenarios; 3. Use recursion and loops to create parameters and assignments one by one.
The operating environment of this tutorial: Windows 10 system, JavaScript version 1.8.5, Dell G3 computer.
Since the Object type and the Array type are reference types, and the mutual assignment of reference types between variables is to assign the pointer to the memory to the past, this will lead to, When the data of b is changed, the data of a will be changed together.
In the actual development process, there are many times when it is necessary to disconnect the connection between two variables, so deep cloning needs to be used to disconnect this connection.
This method is the simplest and most convenient method, but it can only deep clone one layer and reference the second layer. Still pointing to the original location.
This method is also relatively simple and can achieve multi-layer deep cloning, but it cannot be copied. function cannot be applied to all scenarios.
Be able to completely copy an object
// 深克隆function deepCopy(value) { if(value instanceof Function)return value else if (value instanceof Array) { var newValue = [] for (let i = 0; i <p><img src="https://img.php.cn/upload/article/000/000/067/3fc1ae60274d26e62d618c40961c7d0f-3.png" alt="How to implement deep cloning in javascript"></p> <p>Related recommendations: <a href="https://www.php.cn/course/list/17.html" target="_blank">javascript learning tutorial</a></p>
The above is the detailed content of How to implement deep cloning in javascript. For more information, please follow other related articles on the PHP Chinese website!