当前位置:网站首页>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 .
边栏推荐
- Bidding promotion process
- A Cooperative Approach to Particle Swarm Optimization
- Basic operations of databases and tables ----- unique constraints
- Comments on flowable source code (XXXV) timer activation process definition processor, process instance migration job processor
- Blue Bridge Cup embedded_ STM32 learning_ Key_ Explain in detail
- Basic operations of database and table ----- set the fields of the table to be automatically added
- 【Flask】官方教程(Tutorial)-part2:蓝图-视图、模板、静态文件
- How does redis implement multiple zones?
- [technology development -28]: overview of information and communication network, new technology forms, high-quality development of information and communication industry
- [flask] response, session and message flashing
猜你喜欢
NLP fourth paradigm: overview of prompt [pre train, prompt, predict] [Liu Pengfei]
[flask] official tutorial -part2: Blueprint - view, template, static file
【Flask】官方教程(Tutorial)-part3:blog蓝图、项目可安装化
A Cooperative Approach to Particle Swarm Optimization
Huawei Hrbrid interface and VLAN division based on IP
Kubernetes stateless application expansion and contraction capacity
【SSRF-01】服务器端请求伪造漏洞原理及利用实例
[技术发展-28]:信息通信网大全、新的技术形态、信息通信行业高质量发展概览
Publish your own toolkit notes using NPM
02. Go language development environment configuration
随机推荐
Dynamics 365 开发协作最佳实践思考
500 lines of code to understand the principle of mecached cache client driver
Flowable source code comments (36) process instance migration status job processor, BPMN history cleanup job processor, external worker task completion job processor
Superfluid_ HQ hacked analysis
[flask] static file and template rendering
ctf. Show PHP feature (89~110)
How does redis implement multiple zones?
[the most complete in the whole network] |mysql explain full interpretation
竞价推广流程
Unity VR resource flash surface in scene
【已解决】如何生成漂亮的静态文档说明页
Blue Bridge Cup embedded_ STM32_ New project file_ Explain in detail
一圖看懂!為什麼學校教了你Coding但還是不會的原因...
[le plus complet du réseau] | interprétation complète de MySQL explicite
Bidding promotion process
NLP fourth paradigm: overview of prompt [pre train, prompt, predict] [Liu Pengfei]
module ‘tensorflow. contrib. data‘ has no attribute ‘dataset
leetcode-2. Palindrome judgment
Regular expressions: examples (1)
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