Get the App
SLTechnology News&Howtos  ›  Development  › 

How to realize Deep Clone in javascript

Shulou Source: shulou.com Published: 2022-06-01 06:32:20 09月29日 Update

Editor to share with you how to achieve deep cloning of javascript, I believe that most people do not know much about it, so share this article for your reference, I hope you can learn a lot after reading this article, let's go to understand it!

The method of deep cloning by javascript: 1. Make use of "…" Extension operator, you can clone a layer deeply, but the second layer reference still points to the original location; 2, using JSON, you can achieve multi-layer deep cloning, but can not copy function, can not apply to all scenarios; 3, use recursion and loop to create parameters and assignments one by one.

The operating environment of this tutorial: windows10 system, javascript1.8.5 version, Dell G3 computer.

How to achieve Deep cloning with javascript

Because the Object type and the Array type are reference types, and the mutual assignment of reference types between variables is to assign a pointer to memory in the past, this will cause the data of a to be changed when the data of b is changed.

In the actual development process, there are many times to disconnect the relationship between the two variables, so we need to use deep clones to disconnect this connection.

1. Use the extension operator (… ) to achieve deep cloning

This is the simplest and most convenient way, but only one layer can be cloned deeply, and the reference to the second layer still points to the original location.

2. Use JSON to achieve deep cloning

This method is also relatively simple, and can achieve multi-layer deep cloning, but can not copy function, can not be applied to all scenarios.

3. Use recursion and loop to create parameters and assignments one by one

Can completely copy an object

/ / Deep cloning function deepCopy (value) {if (value instanceof Function) return value else if (value instanceof Array) {var newValue = [] for (let I = 0; I < value.length) + + I) newValue [I] = deepCopy (value [I]) return newValue} else if (value instanceof Object) {var newValue = {} for (let i in value) newValue [I] = deepCopy (value [I]) return newValue} else return value}

The above is all the contents of the article "how to achieve Deep cloning of javascript". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!

Tags: Type point article two-tier location content parameter variable scene multi-tier operator data mode recursion loop convenience simplicity not so much two memory Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno MySQL Redmi Microsoft Linux Huawei