Detailed description of shallow copy and deep copy in js

Detailed description of shallow copy and deep copy in js

Preface:

Before studying the following article, let's briefly understand the knowledge of memory. The following is a brief introduction

1. js memory

js memory, or the memory of most languages ​​​​is divided into stack and heap. The variable values ​​of basic data types are allocated on the stack, and the variable values ​​of reference data types are allocated on the heap. The stack only stores the addresses of specific objects in the heap.

2. Assignment

For basic data types, the assignment operation is a copy, that is, the new and old variables will not affect each other.

var a = 1;
var b = a;
b = 2;
console.log(b); // 2


For reference data types, the assignment operation simply adds a variable in the stack that points to the object in the heap, that is, copies the reference address. The new and old variables will affect each other, that is, if the object value is changed on the new variable, the corresponding value of the old variable will also change.

var a = {
    name: "mike"
};
var b = a;
b.name = "jack";
console.log(a); // {name: "jack"}

3. Shallow copy

For basic data types and data without nested objects, all operations are copy operations, and the new and old variables will not affect each other.

var a = {
    name: "mike"
};
var b = {};
b.name = a.name;
b.name = "jack";
console.log(a) // {name: "mike"}

However, for data with nested objects, a shallow copy only copies the first-level objects, and the values ​​at deeper levels are still copied reference addresses.

var a = {
    name: "mike",
    language:
        first: "english",
        second: "chinese"
    }
};
var b = {};
b.name = a.name;
b.name = "jack";
b.language = a.language;
b.language.first = "japanese"
console.log(a) // { language : {first: "japanese", second: "chinese"}}

js implements shallow copy, the idea is : traverse each attribute of target and assign the attribute name and value to the new variable.
If you understand the meaning of assignment, then in the fourth line of the code, when the value of target[key] is an object, the new variable is assigned through assignment, which essentially copies the address of the reference data type in the heap. It is not difficult to understand why shallow copy has different results for whether it is a nested object.

function shallowCopy(target) {
    let result = {};
    for (const key in target) {
        result[key] = target[key];
    }
    return result;
}

4. Deep Copy

A deep copy is a complete copy, and the new and old variables will not affect each other.
There are different processing methods for whether the parameter is an object. If it is an object, each attribute and value of the object is assigned and then processed recursively; otherwise, it is returned directly.

function clone(target) {
    if (typeof target === "object") {
        //Judge whether it is an array let result = Array.isArray(target)? [] : {};
        for (const key in target) {
            result[key] = clone(target[key]);
        }
        return result;
    } else {
        return target;
    }
}

This is the end of this detailed article about shallow copy and deep copy of assignment in js. For more relevant content about shallow copy and deep copy of assignment in js, please search previous articles on 123WORDPRESS.COM or continue to browse the related articles below. I hope you will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Summary of common usage of javascript destructuring assignment under ES6
  • An article to help you understand JavaScript destructuring assignment
  • A practical guide to JavaScript destructuring assignment
  • JavaScript destructuring assignment detailed explanation
  • JS ES new feature of variable decoupling assignment
  • 5 common scenarios and examples of JavaScript destructuring assignment
  • Detailed explanation of JS ES6 variable destructuring assignment
  • JavaScript assignment, the difference between shallow copy and deep copy

<<:  UDP DUP timeout UPD port status detection code example

>>:  How MySQL Select Statement is Executed

Recommend

Implementation example of JS native double-column shuttle selection box

Table of contents When to use Structural branches...

Making a simple game engine with React Native

Table of contents Introduction Get started A brie...

Detailed example of using the distinct method in MySQL

A distinct Meaning: distinct is used to query the...

Universal solution for MySQL failure to start under Windows system

MySQL startup error Before installing MySQL on Wi...

How to quickly deploy Redis as a Docker container

Table of contents getting Started Data storage Co...

View the dependent libraries of so or executable programs under linux

View the dependent libraries of so or executable ...

Example code for implementing bottom alignment in multiple ways with CSS

Due to the company's business requirements, t...

mysql obtains statistical data within a specified time period

mysql obtains statistical data within a specified...

Vue's new partner TypeScript quick start practice record

Table of contents 1. Build using the official sca...

How to configure redis sentinel mode in Docker (on multiple servers)

Table of contents Preface condition Install Docke...

Detailed explanation of Vue's monitoring properties

Table of contents Vue monitor properties What is ...

Query process and optimization method of (JOIN/ORDER BY) statement in MySQL

The EXPLAIN statement is introduced in MySQL quer...

Detailed explanation of Django+Vue+Docker to build an interface testing platform

1. Two words at the beginning Hello everyone, my ...

The difference between MySQL user management and PostgreSQL user management

1. MySQL User Management [Example 1.1] Log in to ...

Detailed explanation of browser negotiation cache process based on nginx

This article mainly introduces the detailed proce...