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

Vue.$set failure pitfall discovery and solution

I accidentally found that Vue.$set was invalid in...

Analysis of the process of building a LAN server based on http.server

I don’t know if you have ever encountered such a ...

Axios cancel request and avoid duplicate requests

Table of contents origin status quo Cancel reques...

How to install Windows Server 2008 R2 on Dell R720 server

Note: All pictures in this article are collected ...

Cross-database association query method in MySQL

Business scenario: querying tables in different d...

Some tips on website design

In fact, we have been hearing a lot about web des...

How React Hooks Work

Table of contents 1. React Hooks vs. Pure Functio...

Introduction and examples of hidden fields in HTML

Basic syntax: <input type="hidden" na...

Detailed analysis of the parameter file my.cnf of MySQL in Ubuntu

Preface Based on my understanding of MySQL, I thi...

How to create a flame effect using CSS

The main text starts below. 123WORDPRESS.COM Down...

How to deal with garbled characters in Mysql database

In MySQL, database garbled characters can general...

The process of installing SVN on Ubuntu 16.04.5LTS

This article briefly introduces the process of se...

Ubuntu 20.04 firewall settings simple tutorial (novice)

Preface In today's increasingly convenient In...