当前位置:网站首页>This time, thoroughly understand the deep copy
This time, thoroughly understand the deep copy
2022-07-06 01:47:00 【Always--Learning】
Why learn deep copy ?
Before introducing deep copy , First of all, we need to know why we should learn deep copy , It's not just because it's a common interview question , Also because in the actual development , We often encounter scenarios that require deep copying , Therefore, we must master the problem of deep copy , Deep copy involves many knowledge points , The learning of this knowledge point can help us quickly expand and consolidate other relevant knowledge points .
Basic data types and reference data types
Before introducing deep copy , We must first understand the concepts and differences between basic data types and reference data types .
The basic data type has no subtypes , No more splitting , But complex data types also have subtypes . Different data types , This results in different storage methods of data in memory , Simple data types are stored on the stack , Stored is a value , If it's a complex data type , Store in the pile , What is stored is an address , It is precisely because of the different storage methods , As a result, when we copy objects , Sometimes a shallow copy is needed , Sometimes you need a deep copy .
Basic data type
Typical basic data types are as follows :
- undefined
- number
- boolean
- bigint
- symbol
- null
- string
Reference data type
Typical reference data types mainly include the following :
- Object
- Array
- Map
- Set
- Date
- Regexp
- Function
The difference between deep copy and shallow copy
For shallow copies : If the attribute is a basic type , What is copied is the corresponding value , If the property is a reference type , Copy is the corresponding memory address , So at this time, if you modify the attribute of the reference type in the new copy object, it will affect the attribute in the original object .
For deep copy : If the attribute is a basic type , Copy the corresponding value , If it's a reference type , A new space will be opened from the heap memory to store new objects , Modifying the new object will not affect the original object .
How to realize deep copy
Mode one : adopt JSON.parse(JSON.stringify(obj))
The following is an example of how to JSON.parse(JSON.stringify(obj)) An example of implementing deep copy
let obj = {
id:666,
info:{
name:" Zhang San ",
age:24
}
}
let obj2 = JSON.parse(JSON.stringify(obj))// Complex data types can also be used JSON.parse(JSON.stringify(obj))
obj2.info.age = 100;
obj.info.age //24
obj2.info.age // 100
It should be noted that JSON.parse This method is not omnipotent , Because the supported data types are limited , For example, only support object、array、string、number、boolean、null etc. , I won't support it undefined、function、 Regular 、Date、 ring obj、map、set Equal copy .
Mode two : recursive copying
The so-called recursive copy is that we copy the reference data types that cannot be copied directly in decibel by recursion . It's mainly about Array、Function、RegExp、Date、Map、Set And so on , At the same time, you need to consider circular references and filter out the attributes on the prototype .
function deepClone(target, cache = new Map()) {
if (cache.get(target)) {
return cache.get(target)
}
if (target instanceof Object) {
let dist;
if (target instanceof Array) {
// Copy an array
dist = [];
} else if (target instanceof Function) {
// Copy function
dist = function () {
return target.call(this, ...arguments);
};
} else if (target instanceof RegExp) {
// Copy regular expressions
dist = new RegExp(target.source, target.flags);
} else if (target instanceof Date) {
// Copy date function
dist = new Date(target);
} else if (target instanceof Map) {
// Copy Map
dist = new Map(target);
} else if (target instanceof Set) {
// Copy Set
dist = new Set(target);
} else {
// Copy ordinary objects
dist = {
};
}
// Take the attribute and the copied value as a map
cache.set(target, dist);
for (let key in target) {
// Filter out the attributes on the prototype
if (target.hasOwnProperty(key)) {
dist[key] = deepClone(target[key], cache);
}
}
return dist;
} else {
return target;
}
}
summary
The essence of the implementation of deep copy is to consider how to implement deep copy for different data types , Solve problems according to the characteristics of different types .
边栏推荐
- 3D视觉——4.手势识别(Gesture Recognition)入门——使用MediaPipe含单帧(Singel Frame)和实时视频(Real-Time Video)
- Paddle框架:PaddleNLP概述【飛槳自然語言處理開發庫】
- Regular expressions: examples (1)
- Flowable source code comments (36) process instance migration status job processor, BPMN history cleanup job processor, external worker task completion job processor
- Unity VR solves the problem that the handle ray keeps flashing after touching the button of the UI
- dried food! Accelerating sparse neural network through hardware and software co design
- It's wrong to install PHP zbarcode extension. I don't know if any God can help me solve it. 7.3 for PHP environment
- leetcode-2.回文判断
- 【Flask】官方教程(Tutorial)-part2:蓝图-视图、模板、静态文件
- Folio.ink 免费、快速、易用的图片分享工具
猜你喜欢

Mongodb problem set

leetcode刷题_反转字符串中的元音字母

Une image! Pourquoi l'école t'a - t - elle appris à coder, mais pourquoi pas...

Redis-列表

How does redis implement multiple zones?

Basic operations of databases and tables ----- non empty constraints

A Cooperative Approach to Particle Swarm Optimization

MUX VLAN configuration
![[flask] official tutorial -part2: Blueprint - view, template, static file](/img/bd/a736d45d7154119e75428f227af202.png)
[flask] official tutorial -part2: Blueprint - view, template, static file

You are using pip version 21.1.1; however, version 22.0.3 is available. You should consider upgradin
随机推荐
Luo Gu P1170 Bugs Bunny and Hunter
Leetcode3. Implement strstr()
Reasonable and sensible
Flowable source code comments (36) process instance migration status job processor, BPMN history cleanup job processor, external worker task completion job processor
剑指 Offer 12. 矩阵中的路径
Alibaba canal usage details (pit draining version)_ MySQL and ES data synchronization
leetcode-2. Palindrome judgment
Get the relevant information of ID card through PHP, get the zodiac, get the constellation, get the age, and get the gender
Paddle框架:PaddleNLP概述【飞桨自然语言处理开发库】
Blue Bridge Cup embedded_ STM32_ New project file_ Explain in detail
Paddle框架:PaddleNLP概述【飛槳自然語言處理開發庫】
National intangible cultural heritage inheritor HD Wang's shadow digital collection of "Four Beauties" made an amazing debut!
竞价推广流程
[technology development -28]: overview of information and communication network, new technology forms, high-quality development of information and communication industry
Format code_ What does formatting code mean
Redis key operation
leetcode3、實現 strStr()
【Flask】静态文件与模板渲染
Force buckle 9 palindromes
Bidding promotion process