Before understanding deep and shallow copies , Let's sort it out first :

JavaScript in , Divided into basic data types ( Original value ) And complex types ( object ), At the same time, there are several data types under their respective data types

Basic data type

Numbers Number character string String Boolean Boolean Null Undefined Symbols BigInt

The basic data type is in memory , Is stored on the stack Stack

In the data structure

  • The allocated space life cycle of stack on memory is very short , When the variable is used , The method is released after execution , So in js among , After the variable is used , Basically recycled ,
  • There is an exception , In the case of closures , Variables always exist in memory and are not released .
  • Stack storage has first in and last out , The characteristics of LIFO : 1,2,3,4,5,6 => 6,5,4,3,2,1

Reference data type

date Dete, object Object, Array Array, Method Function, Regular regex, Collection with keys :Maps, Sets, WeakMaps, WeakSets

Reference data type and heap memory heap Some of the relationships
  • stay JavaScript in , Direct access to locations in heap memory... Is not allowed , You cannot directly manipulate the heap memory space of an object .
  • The reference address of the object is stored in stack memory , In our daily coding process , When manipulating objects , Read the reference address of the existing stack memory of the object, not the object in the heap , The values of reference types are accessed by reference .

JavaScript Simple schematic illustration of heap memory and stack memory in

The following operations on objects , You can think with reference to the above figure

Shallow copy - Deep copy

Shallow copy

It just copies the properties of a certain layer , Or a certain layer , Not all copied to another object

let userInfo = {
name: "zhangsan",
age: "29",
say: function () {
console.log("hello");
},
child: [
{
name: "zhangsan01",
},
],
};
  1. Object to deconstruct , Only the first level objects can be copied
//  Object to deconstruct ...
let info = { ...userInfo };
info.name = "lisi";
info.child.name = "lisi001";
info.say(); console.log("userInfo", userInfo);
console.log("info", info); userInfo and info Medium child.name It's all changed to ---->"lisi001"
  1. Object.assign() The first layer is deep copy , After the secondary attribute is the shallow copy
let info = {};
Object.assign(info, userInfo);
info.name = "lisi";
info.child.name = "lisi001";
console.log("userInfo", userInfo);
console.log("info", info);
  1. JSON.parse(JSON.stringify());

    Objects can be copied , But when the attribute is function when , Not copied to the new object , So in the daily development process , Involving array objects , Use JSON.parse(JSON.stringify()); No problem
let info = JSON.parse(JSON.stringify(userInfo));
info.name = "lisi";
info.child.name = "lisi001";
console.log("userInfo", userInfo);
console.log("info", info);
  1. for in, The first layer can be copied , The second layer is modified , Or the reference address used , The objects before and after have changed
let info = {};
for (let key in userInfo) {
info[key] = userInfo[key];
}
info.name = "lisi";
info.child.name = "lisi001";
console.log("userInfo", userInfo);
console.log("info", info);

Summary of shallow copy

The above shallow copy method , Some copies can only copy the first layer , Some can be copied in multiple layers ,

But when the attribute type is a method , It's still a shallow copy ,

So we are developing , Use shallow copy , We need to pay attention to , meanwhile , Copy out function, Similar to regular ,date And other data types are not listed one by one , Interested students can write some by themselves demo, To verify more complex and richer data types .

Deep copy

All properties are copied to the new object

  1. Use recursion to traverse each attribute , During recursive traversal , Process and copy for each data type
  2. lodash Deep copy method , Interested students , You can read lodash Deep copy of the implementation source code

Document address : Deep copy cloneDeephttps://www.lodashjs.com/docs/lodash.cloneDeep

  1. More ways , To be added

ending

  • When data types are complex , All in the operation stack memory Stack Memory address of , Pointer to the object in heap memory heap The data of .

  • The object passed in is using the object literal {} The object created is still the object generated by the constructor

  • If the object is created by a constructor , Do you want to copy the attributes on the prototype chain

  • If you want to copy the attributes on the prototype chain , Then, if there are multiple attributes with the same name on the prototype chain , Keep which

  • Data type for , The data type of the property , Respective defects , Applicable business scenarios , Make your own wheels or Use native methods , Tool class


Source code address

Article personal blog address :javaScript Medium deep copy and shallow copy

Welcome to the official account : Program ape boo , Update some front-end introductory articles from time to time

It's not easy to create , Please indicate the source and the author of the reprint .

javaScript More related articles about deep copy and shallow copy

  1. javascript Deep copy and shallow copy

    javascript Deep copy and shallow copy Deep copy and shallow copy Assignment and depth / Shallow copy difference The implementation of shallow copy 1.Object.assign() 2. function library lodash Of _.clone Method 3. Expand operator ... 4 ...

  2. Read javascript Deep copy and shallow copy

    1. Know deep copy and shallow copy javascript In general, there are two kinds of replication: by value and by reference , Passing by value is the basic data type (Number,String,Boolean,Null,Undefined), It is usually stored in memory ...

  3. JavaScript The difference and implementation between deep copy and shallow copy

    How to distinguish between deep copy and shallow copy , In short, objects B Copied the object A, If the object A And the object B Share one object , object B Change the object A With change, this is the shallow copy : But if the object B Copied the object A, But the object A And the object B It's separate. , So it's a deep copy Basic numbers ...

  4. JavaScript Understanding of deep copy and shallow copy

    This is how individuals understand deep copy and shallow copy : That is the assumption. B Copy the A, When modifying A when , see B Will it change , If B And then it changed , It means it's a shallow copy , Short hand , If B It hasn't changed , That's deep copy , Support oneself . Let's take a look at my shallow chestnuts : let ...

  5. javaScript Deep copy 、 Shallow copy

    stay  JS  There are some basic types in this book, like Number.String.Boolean, And objects are things like this { name: 'Larry', skill: 'Node.js' }, The biggest difference between objects and basic types is that they ...

  6. JavaScript Deep copy and light copy

    1. Basic types and object type The biggest difference between them is the way they transmit values . The basic type is pass value An object type is a reference . Make a copy here obj be called obj2, It's modified here obj2 Of b by 100 It was also modified obj1.b. ...

  7. JS JavaScript Deep copy 、 Shallow copy

    Shallow copy : Shallow copy just copies the memory address , If the object in the original address changes , The shallow copy object will change accordingly . Deep copy : Opened up a new memory to store the address and the object pointed to by the address , Any object of the original address has changed , The object copied from the deep copy remains unchanged . Shallow copy number ...

  8. Come and play, too javascript Object deep copy , Shallow copy

    I often see discussions c# Deep copy , Shallow copy blogs , lately js More writing , So come and play js Object copy of . Here's Wikipedia's explanation of deep and shallow copies : Shallow copy One method of copying an object is ...

  9. javascript Object deep copy , Shallow copy , Support array

    javascript Object deep copy , Shallow copy , Support array I often see discussions c# Deep copy , Shallow copy blogs , lately js More writing , So come and play js Object copy of . Here's Wikipedia's explanation of deep and shallow copies : Shallow copy One meth ...

  10. JavaScript Deep and shallow copies

    Preface We often encounter the operation array in our work . About the object , You're sure to put the original array . Object to carry out ‘ Backup ’ When you really operate on it, you will find that the backup has also changed , At this time, you look confused , Then why , It has been backed up , How to back up the array . Objects also change . If ...

Random recommendation

  1. HTML2

    1. IIS It's a software , stay " Client server " In the model , It is server-side software , It mainly provides services based on HTTP Document services , Mainly WWW     Sending of , as well as FTP File download service . VS Provides " ...

  2. css form Form group alignment

    2014 year 7 month 1 Japan 15:31:17 Write for the first time css, Forgive me css: .form-box .form-group .form-label {text-align: right; width: 200p ...

  3. Blog test : The blog system i94web beta1.0 Request test

    The blog hasn't been updated much recently , Because I've been working on the code , I wrote a small blog system :i94web, Rush to release beta1.0, I ask you to test all kinds of vulnerabilities . Take a few screenshots first . home page : The sidebar : Article page : Background release : Address of the test :htt ...

  4. Python Basics File operations

    Conversion between strings and bytes # utf-8 A Chinese character Three bytes # gbk A Chinese character Two bytes # String to byte print(bytes(' Chinese characters ', encoding='utf-8'))print ...

  5. ASP.NET General permission verification component implementation

    Sofa (SF) General permission verification component The opening This article introduces the implementation code of general permission verification , It is divided into import parameters . analysis XML. according to XML Configure to process . Return results . Code architecture diagram 1.   Class introduction 1.SFWebPermissio ...

  6. dialog Get focus

    The pop-up layer is a iframe openWindow:function (options) { var url = options.url; url += url.indexOf("?" ...

  7. CentOS7 install Hadoop Cluster environment

    First install and configure according to the previous article CentOS as well as zookeeper http://www.cnblogs.com/dopeter/p/4609276.html This chapter is introduced in CentOS build Hadoop Cluster environment ...

  8. WebSocket Study and use

    1.WebSocket What is it? WebSocket It's one in a single TCP A protocol for full duplex communication over a connection , Its purpose is to establish an unrestricted two-way communication channel between browser and server , So that the server can actively send messages to the browser . stay HTML ...

  9. 10.2.0.5 Environmental Science dg test logminer Mining log analysis

    cause : customer demand , The database is normal. The total daily log switch is 20 within , One day the total number of log switches , achieve 30, The customer recommends using Logminer Log mining analysis , What application causes the problem . explain : Use logminer Log mining , Can only ...

  10. Singer Learning one Use Singer Conduct mysql 2 postgres Data conversion

    Singer Because of the version , The recommended way to run is to use virtualenv, about taps&& target It's all about This method is recommended , Otherwise, the problem of package compatibility is too much trouble remarks : Use docker- ...