当前位置:网站首页>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 .

边栏推荐
- What about data leakage? " Watson k'7 moves to eliminate security threats
- Jasypt configuration file encryption | quick start | actual combat
- MMSeg——Mutli-view时序数据检查与可视化
- 记录一下在深度学习-一些bug处理
- NFT value and white paper acquisition
- ::ffff:192.168.31.101 是一个什么地址?
- aspx 简单的用户登录
- ETCD数据库源码分析——集群间网络层客户端peerRt
- Don't know these four caching modes, dare you say you understand caching?
- About the problem and solution of 403 error in wampserver
猜你喜欢

Operational research 68 | the latest impact factors in 2022 were officially released. Changes in journals in the field of rapid care
Jetpack Compose入门到精通

When using Tencent cloud for the first time, you can only use webshell connection instead of SSH connection.

【云资源】云资源安全管理用什么软件好?为什么?

NFT value and white paper acquisition

Solve the problem of invalid uni app configuration page and tabbar

【华南理工大学】考研初试复试资料分享

About the problem and solution of 403 error in wampserver

Convolutional Neural Networks简述

Huawei push service content, read notes
随机推荐
[server data recovery] a case of RAID5 data recovery stored in a brand of server
Convolutional Neural Networks简述
4年工作经验,多线程间的5种通信方式都说不出来,你敢信?
Rk3566 add LED
[cloud resources] what software is good for cloud resource security management? Why?
How to divide a large 'tar' archive file into multiple files of a specific size
leetcode 10. Regular expression matching regular expression matching (difficult)
【云资源】云资源安全管理用什么软件好?为什么?
Interviewer soul torture: why does the code specification require SQL statements not to have too many joins?
Kafaka log collection
Summit review | baowanda - an integrated data security protection system driven by compliance and security
kafaka 日志收集
Intranet penetration tool NetApp
Embedded software architecture design - message interaction
2022司钻(钻井)考试题库及模拟考试
[machine learning notes] how to solve over fitting and under fitting
记录一下在深度学习-一些bug处理
那些考研后才知道的事
53. 最大子数组和:给你一个整数数组 nums ,请你找出一个具有最大和的连续子数组(子数组最少包含一个元素),返回其最大和。
MySQL if else use case use