Home > Web Front-end > Front-end Q&A > How to implement deep cloning in javascript

How to implement deep cloning in javascript

WBOY
Release: 2022-03-10 11:57:11
Original
2203 people have browsed it

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>
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template