Let you understand the deep copy of js

Let you understand the deep copy of js

js deep copy

Before we get to the point, we need to understand how data is stored.

Data storage method

Before we talk about it, we must first know how value types and reference types are stored.

There are two types of data in JavaScript.

Value types : String , Number , Boolean , Null , Undefined , Symbol .

A simple data segment stored in the stack memory, the data size is determined, and the memory space size can be allocated.

Reference data types : Object , (Array , Function .

For objects stored in the heap memory, a pointer is stored in the stack memory, and this pointer points to a location in the heap memory. Then get the required data from the heap memory.

The storage is as follows:

insert image description here

What is shallow/deep copy

After talking about the storage method, let's talk about shallow copy and deep copy

Copy is what we often call copy, ctrl+c, ctrl+v, so let's take a look at an example

When we assign values ​​to value types and reference types respectively.

     var a = 5
     var b = a
     b += 5
     console.log('a=' + a,'b=' + b)
     var arr = [1,2,3]
     var brr = arr
     brr.push(10)
     console.log("arr is",arr)
     console.log("brr is",brr)

insert image description here

Phenomenon : We found that the value types did not affect each other, but the array (reference type) brr array changed the arr array when adding elements.

Explanation and analysis : Shallow copy only occurs on reference types. If a simple assignment is performed on a reference type, only a pointer to the heap memory is assigned. This is called a shallow copy. A deep copy is a complete copy of a reference type, not an address pointer.

Take a shallow copy of the following schematic:

insert image description here

Common deep copy implementations

So when we assign reference types, we must not make shallow copies, which will affect the original data. Then we need to do a deep copy

1. Through JSON.stringify and JSON.parse

Arrays and objects can be deeply copied, but functions cannot be copied. Nested copies of objects or arrays can be made.

Disadvantage : It is impossible to achieve deep copy of methods in objects

use :

     var brr = JSON.parse(JSON.stringify(arr))

example:

  var arr = {
         name: 'Romantic Coder',
         age: 20,
         address: ['jiangxi', 'changsha'],
         friends:
             friend1: 'Zhang San',
             friend2: 'Li Si'
         },
         function(){
             console.log("I am the object of romanticism")
         }
     }
     var brr = JSON.parse(JSON.stringify(arr))
     brr.name='Zhang San, the lawless criminal'
     brr.adress[0]='Changsha'
     console.log("arr is", arr)
     console.log("brr is", brr)

insert image description here

2. Spread Operator

The structure assignment feature method of the object is utilized.

Disadvantages : No deep copy of nested objects in the object, which is equivalent to deep copying only one layer of reference objects

use:

     var brr = {...arr}

example:

  var arr = {
         name: 'Romantic Coder',
         age: 20,
         address: ['jiangxi', 'changsha'],
         friends:
             friend1: 'Zhang San',
             friend2: 'Li Si'
         },
         function(){
             console.log("I am the object of romanticism")
         }
     }
     var brr = {...arr}
     brr.name='Zhang San, the lawless criminal'
     brr.adress[0]='Changsha'
     console.log("arr is", arr)
     console.log("brr is", brr)

insert image description here

3. Handwritten recursive deep copy function

Perfect solution

function:

  //Use recursion to implement deep copy function deepClone(obj) {
         //Determine whether the copied obj is an object or an array var objClone = Array.isArray(obj) ? [] : {};
         if (obj && typeof obj === "object") { //obj cannot be empty and must be an object or an array because null is also an object
             for (key in obj) {
                 if (obj.hasOwnProperty(key)) {
                     if (obj[key] && typeof obj[key] === "object") { //The attribute value in obj is not empty and it is still an object, make a deep copy objClone[key] = deepClone(obj[key]); //Recursively make a deep copy } else {
                         objClone[key] = obj[key]; //direct copy}
                 }
             }
         }
         return objClone;
     }

example:

      var arr = {
         name: 'Romantic Coder',
         age: 20,
         address: ['jiangxi', 'changsha'],
         friends:
             friend1: 'Zhang San',
             friend2: 'Li Si'
         },
         fun: function(){
             console.log("I am the object of " + this.name + "")
         }
     }
     var brr = deepClone(arr)
     brr.name = 'Outlaw Zhang San'
     brr.adress[0] = 'Changsha'
     console.log("arr is", arr)
     arr.fun()
     console.log("brr is", brr)
     brr.fun()
 ​
     //Use recursion to implement deep copy function deepClone(obj) {
         //Determine whether the copied obj is an object or an array var objClone = Array.isArray(obj) ? [] : {};
         if (obj && typeof obj === "object") { //obj cannot be empty and must be an object or an array because null is also an object
             for (key in obj) {
                 if (obj.hasOwnProperty(key)) {
                     if (obj[key] && typeof obj[key] === "object") { //The attribute value in obj is not empty and it is still an object, make a deep copy objClone[key] = deepClone(obj[key]); //Recursively make a deep copy } else {
                         objClone[key] = obj[key]; //direct copy}
                 }
             }
         }
         return objClone;
     }

insert image description here

Summarize

This article ends here. I hope it can be helpful to you. I also hope that you can pay more attention to more content on 123WORDPRESS.COM!

You may also be interested in:
  • Detailed explanation of shallow copy and deep copy of js objects
  • Two methods of deep copy and shallow copy of JavaScript array
  • Deep copy of objects in JavaScript
  • Analysis of JS's method of implementing deep copy of arrays
  • Detailed explanation of JavaScript deep copy (deepClone)
  • js deep copy function
  • JavaScript basics: shallow and deep copying (shallow and deep copying)
  • Detailed explanation of code for implementing shallow copy and deep copy in JS
  • javascript deep copy
  • Several examples of implementing JavaScript deep copy

<<:  Who is a User Experience Designer?

>>:  CSS achieves the effect of rotating the outermost layer of a multi-layer nested structure while keeping other layers unchanged

Recommend

JavaScript deshaking and throttling examples

Table of contents Stabilization Throttling: Anti-...

How to encapsulate axios request with vue

In fact, it is very simple to encapsulate axios i...

Teach you how to deploy Vue project with Docker

1.Write in front: As a lightweight virtualization...

Pitfalls and solutions for upgrading MySQL 5.7.23 in CentOS 7

Preface Recently, I found a pitfall in upgrading ...

Vue3.0 implements the magnifying glass effect case study

The effect to be achieved is: fixed zoom in twice...

MySQL master-slave principle and configuration details

MySQL master-slave configuration and principle, f...

How to use Nginx to proxy multiple application sites in Docker

Preface What is the role of an agent? - Multiple ...

Review of the best web design works in 2012 [Part 1]

At the beginning of the new year, I would like to...

The use of vue directive v-bind and points to note

Table of contents 1. v-bind: can bind some data t...

CSS achieves the effect of two elements blending (sticky effect)

I remember that a few years ago, there was an int...

Steps for importing tens of millions of data into MySQL using .Net Core

Table of contents Preliminary preparation Impleme...

How to view the storage location of MySQL data files

We may have a question: After we install MySQL lo...