当前位置:网站首页>Deep copy is hard
Deep copy is hard
2022-07-05 13:50:00 【wade3po】
I already understand the principle of deep copy and shallow copy , I've shared it before . It's just the method of deep copy and shallow copy, but I've never really understood it .
Think about the previous interview , When it comes to deep copy and shallow copy , It's all about principles , Ask about the method , Open your mouth JSON.parse and JSON.stringify, If there is a function, copy it recursively . But never write recursive or circular copy function .
Today I wrote the function of deep copy data , It's hard to find deep copy , Just a deep copy of the data makes my brain feel unbearable , Not to mention that some big guys mentioned the prototype chain 、dom、RegExp、 function 、 Whether to copy or how to deal with the built-in functions of the browser , Plus compatibility , After going out, I dare not say that I can write deep copy functions any more .
Today is not a good deep copy function , Just write a deep copy of data processing , Although for json A deep copy of an object JSON.parse and JSON.stringify It's the simplest , Just to see the world a little bit .
First, a recursive deep copy function :
function clone(data) {
var target = data;
if(isObject(data)){
target = {};
for(var i in data) {
target[i] = clone(data[i])
}
}
if(isArray(data)){
target = [];
for (let i = 0; i < data.length; i++) {
target[i] = clone(data[i])
}
}
return target;
}
function isObject(x){
return Object.prototype.toString.call(x) === '[object Object]';
}
function isArray(x){
return Object.prototype.toString.call(x) === '[object Array]';
}
It's simple , Determine whether the parameters passed in are arrays or objects , Here, the judgment of array or object is more strict , If so, loop recursively to copy the sub object respectively . It's just a deep copy of objects and arrays .for in We all know that it will traverse itself and the enumerable properties on the prototype chain , Sometimes we don't want to copy these . So the compatibility here is in for in Inside plus data.hasOwnProperty The judgment of the .
Basically recursive copies can be understood , But if there are too many levels of data , There will be a stack explosion :
Maximum call stack size exceeded
Include JSON.parse and JSON.stringify It will be .
This is the time to cycle deep copy , Go straight to the code :
function cloneLoop(x) {
let target = '';
if(isObject(x)){
target = {};
};
if(isArray(x)){
target = [];
}
const loopList = [
{
parent: target,
key: undefined,
data: x,
}
];
while(loopList.length) {
const node = loopList.pop();
const parent = node.parent;
const key = node.key;
const data = node.data;
let res = parent;
if(typeof key !== 'undefined'){
if(isObject(data)) {
res = parent[key] = {};
};
if(isArray(data)) {
res = parent[key] = [];
}
}
if(isObject(data)){
for(let k in data) {
initLoopList(data[k], k, res);
}
}
if(isArray(data)){
for (let i = 0; i < data.length; i++) {
initLoopList(data[i], i, res);
}
}
}
function initLoopList(val, key, res) {
if (isObject(val) || isArray(val)) {
loopList.push({
parent: res,
key: key,
data: val,
});
} else {
res[key] = val;
}
}
return target;
}
function isObject(val){
return Object.prototype.toString.call(val) === '[object Object]'
}
function isArray(val){
return Object.prototype.toString.call(val) === '[object Array]'
}
I don't even know how to annotate this function , The essence is these two quotations :
res = parent[key] = {};
res = parent[key] = [];
It's just a little bit of a detour around references , You can understand it for yourself .
Deep copy can only be understood to this extent for the time being , Of course , Generally speaking, data doesn't have such a deep hierarchy . This is just the simplest copy of an array object , There's no function involved 、dom Or prototype chain , Not even references to data are taken into account , such as :
let a = {};
let b = {b:b, c:c};
In this case, you have to consider whether to keep the reference or create a new one .
Finally, the concept of serialization and deserialization is proposed , What we share today is actually data that can be serialized and serialized . Baidu Encyclopedia above the definition of serialization :
Serialization is the process of converting the state information of an object into a form that can be stored or transmitted . During serialization , Object writes its current state to a temporary or persistent store . in the future , You can read or deserialize the state of an object from the store , Recreate the object .
Different languages have different ways , On Baidu Encyclopedia Java The serialization of is converted to binary , Deserialization is the conversion of binary to object . and JavaScript I understand serialization as the transformation of objects into strings , Send serialization to turn a string into an object .
边栏推荐
- Laravel framework operation error: no application encryption key has been specified
- ZABBIX monitoring
- MySQL if else use case use
- Jetpack compose introduction to mastery
- Self built shooting range 2022
- 几款分布式数据库的对比
- TortoiseSVN使用情形、安装与使用
- How to apply the updated fluent 3.0 to applet development
- Redis6 master-slave replication and clustering
- 基于微信小程序的订餐系统
猜你喜欢
Jasypt configuration file encryption | quick start | actual combat
[server data recovery] a case of RAID5 data recovery stored in a brand of server
Binder communication process and servicemanager creation process
PHP basic syntax
内网穿透工具 netapp
Introduction to Chapter 8 proof problem of njupt "Xin'an numeral base"
UE源码阅读[1]---由问题入手UE中的延迟渲染
Zibll theme external chain redirection go page beautification tutorial
Intranet penetration tool NetApp
How to apply the updated fluent 3.0 to applet development
随机推荐
Datapipeline was selected into the 2022 digital intelligence atlas and database development report of China Academy of communications and communications
Self built shooting range 2022
Pancake Bulldog robot V2 (code optimized)
Win10 - lightweight gadget
Catch all asynchronous artifact completable future
uplad_ Labs first three levels
研究生可以不用学英语?只要考研英语或六级分数高!
Scientific running robot pancakeswap clip robot latest detailed tutorial
Log4j utilization correlation
asp.net 读取txt文件
ELK 企业级日志分析系统
The development of speech recognition app with uni app is simple and fast.
内网穿透工具 netapp
Data Lake (VII): Iceberg concept and review what is a data Lake
通讯录(链表实现)
[machine learning notes] several methods of splitting data into training sets and test sets
Introduction to Chapter 8 proof problem of njupt "Xin'an numeral base"
In addition to the root directory, other routes of laravel + xampp are 404 solutions
French scholars: the explicability of counter attack under optimal transmission theory
These 18 websites can make your page background cool