Home  >  Article  >  Web Front-end  >  How to implement deep cloning in javascript

How to implement deep cloning in javascript

WBOY
WBOYOriginal
2022-03-10 11:53:502184browse

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.

How to implement deep cloning in javascript

The operating environment of this tutorial: Windows 10 system, JavaScript version 1.8.5, Dell G3 computer.

How to implement deep cloning in javascript

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.

How to implement deep cloning in javascript
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.

1. Use the extension operator (...) to implement deep cloning

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.

How to implement deep cloning in javascript

2. Use JSON to implement deep cloning

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.

How to implement deep cloning in javascript
3. Use recursion and loops to create parameters and assign values ​​one by one

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn