当前位置:网站首页>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 .
边栏推荐
- Flowable source code comments (36) process instance migration status job processor, BPMN history cleanup job processor, external worker task completion job processor
- MCU lightweight system core
- Competition question 2022-6-26
- leetcode刷题_平方数之和
- Leetcode skimming questions_ Sum of squares
- internship:项目代码所涉及陌生注解及其作用
- Grabbing and sorting out external articles -- status bar [4]
- Dynamics 365 开发协作最佳实践思考
- MUX VLAN configuration
- 同一个 SqlSession 中执行两条一模一样的SQL语句查询得到的 total 数量不一样
猜你喜欢
Folio.ink 免费、快速、易用的图片分享工具

Blue Bridge Cup embedded_ STM32 learning_ Key_ Explain in detail

How does redis implement multiple zones?

XSS learning XSS lab problem solution

Leetcode skimming questions_ Verify palindrome string II

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

Basic operations of databases and tables ----- default constraints

【Flask】官方教程(Tutorial)-part3:blog蓝图、项目可安装化

Extracting key information from TrueType font files

dried food! Accelerating sparse neural network through hardware and software co design
随机推荐
How does Huawei enable debug and how to make an image port
【Flask】官方教程(Tutorial)-part1:项目布局、应用程序设置、定义和访问数据库
剑指 Offer 38. 字符串的排列
Une image! Pourquoi l'école t'a - t - elle appris à coder, mais pourquoi pas...
Computer graduation design PHP enterprise staff training management system
leetcode刷题_反转字符串中的元音字母
01.Go语言介绍
Reasonable and sensible
Leetcode skimming questions_ Verify palindrome string II
竞价推广流程
国家级非遗传承人高清旺《四大美人》皮影数字藏品惊艳亮相!
Redis-字符串类型
Basic operations of database and table ----- delete data table
【Flask】获取请求信息、重定向、错误处理
使用npm发布自己开发的工具包笔记
c#网页打开winform exe
Selenium element positioning (2)
Ali test Open face test
leetcode3、实现 strStr()
【详细】快速实现对象映射的几种方式