当前位置:网站首页>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 .
边栏推荐
- Reasonable and sensible
- Thinking about the best practice of dynamics 365 development collaboration
- leetcode刷题_平方数之和
- Redis list
- Redis key operation
- NLP第四范式:Prompt概述【Pre-train,Prompt(提示),Predict】【刘鹏飞】
- Une image! Pourquoi l'école t'a - t - elle appris à coder, mais pourquoi pas...
- 【全網最全】 |MySQL EXPLAIN 完全解讀
- Paddle框架:PaddleNLP概述【飛槳自然語言處理開發庫】
- 抓包整理外篇——————状态栏[ 四]
猜你喜欢
[flask] official tutorial -part3: blog blueprint, project installability
Cookie concept, basic use, principle, details and Chinese transmission
[solved] how to generate a beautiful static document description page
MUX VLAN configuration
[flask] official tutorial -part2: Blueprint - view, template, static file
02. Go language development environment configuration
【详细】快速实现对象映射的几种方式
Leetcode sum of two numbers
【Flask】官方教程(Tutorial)-part2:蓝图-视图、模板、静态文件
NLP fourth paradigm: overview of prompt [pre train, prompt, predict] [Liu Pengfei]
随机推荐
leetcode-两数之和
Redis-字符串类型
Extracting key information from TrueType font files
TrueType字体文件提取关键信息
Unity VR solves the problem that the handle ray keeps flashing after touching the button of the UI
Initialize MySQL database when docker container starts
Bidding promotion process
晶振是如何起振的?
Sword finger offer 38 Arrangement of strings
【网络攻防实训习题】
Shutter doctor: Xcode installation is incomplete
Leetcode sum of two numbers
Unity learning notes -- 2D one-way platform production method
[network attack and defense training exercises]
Leetcode3. Implement strstr()
【全网最全】 |MySQL EXPLAIN 完全解读
Code review concerns
Mongodb problem set
2022 PMP project management examination agile knowledge points (8)
【Flask】静态文件与模板渲染