当前位置:网站首页>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 .
边栏推荐
- 4年工作经验,多线程间的5种通信方式都说不出来,你敢信?
- leetcode 10. Regular Expression Matching 正则表达式匹配 (困难)
- Integer = = the comparison will unpack automatically. This variable cannot be assigned empty
- PHP generate Poster
- ::ffff:192.168.31.101 是一个什么地址?
- Jasypt configuration file encryption | quick start | actual combat
- 如何把大的‘tar‘存档文件分割成特定大小的多个文件
- [machine learning notes] how to solve over fitting and under fitting
- [machine learning notes] several methods of splitting data into training sets and test sets
- Basic characteristics and isolation level of transactions
猜你喜欢
Rk3566 add LED
Win10 - lightweight gadget
Set up a website with a sense of ceremony, and post it to the public 2/2 through the intranet
华为推送服务内容,阅读笔记
几款分布式数据库的对比
Don't know these four caching modes, dare you say you understand caching?
RK3566添加LED
Attack and defense world crypto WP
Kotlin协程利用CoroutineContext实现网络请求失败后重试逻辑
redis6主从复制及集群
随机推荐
redis6事务和锁机制
Network security - Novice introduction
Prefix, infix, suffix expression "recommended collection"
Redis6 master-slave replication and clustering
Idea remote debugging agent
Record in-depth learning - some bug handling
基于微信小程序的订餐系统
Kotlin collaboration uses coroutinecontext to implement the retry logic after a network request fails
Set up a website with a sense of ceremony, and post it to the public 2/2 through the intranet
Aspx simple user login
Elfk deployment
几款分布式数据库的对比
[js] basic syntax - for loop
Programmer growth Chapter 8: do a good job of testing
Usage, installation and use of TortoiseSVN
Summit review | baowanda - an integrated data security protection system driven by compliance and security
Catch all asynchronous artifact completable future
Log4j utilization correlation
面试官灵魂拷问:为什么代码规范要求 SQL 语句不要过多的 join?
Datapipeline was selected into the 2022 digital intelligence atlas and database development report of China Academy of communications and communications