当前位置:网站首页>实现一个深克隆
实现一个深克隆
2022-08-10 13:07:00 【快乐的蜜蜂】
1.在js中,我们实现最快的克隆方式是什么?
没错,就是我们的
const aaa = {
"aaa": 111
}
const bbb = JSON.parse(JSON.stringify(aaa));
通过JSON.parse跟JSON.stringify方式, 可以实现深克隆的百分之80的场景,
为什么是百分之80的场景呢?
1.当对象的层级太深了,就不会安全的深克隆
2.如果对象中 含有 function 关键字,就会被转化成 “function”, 导致克隆出错
好了, 我们简单的实现一下 深克隆,很简单的几个代码
function cloneDeep(source) {
// 这里判断一下 是不是引用类型
if(typeof source != 'object') return source;
// 这里 来判断 是什么类型
let target = source.constructor == "Array" ? [] : {};
for(let key in source) {
if(source.hasOwnProperty(key)) {
if(source[key] && typeof source[key] == 'object') {
target[key] = cloneDeep(source[key]);
} else {
target[key] = source[key];
}
}
}
return target;
}
const arr1 = {
a: 1,
b: [1,2,3],
c: {
cc: 111
}
};
const arr2 = cloneDeep(arr1);
arr2.b = [1,2,3,4];
arr2.c["ddd"] = 444;
console.log(arr1, "arr1");
console.log(arr2, "arr2");
结果是:
arr2添加的数据, arr1 互不影响, 这个样子就是 简单版的深克隆就写好了
边栏推荐
- A unit test report for CRM One Order Application log
- BEVDet4D: Exploit Temporal Cues in Multi-camera 3D Object Detection 论文笔记
- Efficient and Robust 2D-to-BEV Representation Learning via Geometry-guided Kernel Transformer Paper Notes
- [target detection] small script: extract training set images and labels and update the index
- G1和CMS的三色标记法及漏标问题
- 进程和计划任务管理
- 【百度统计】用户行为分析
- The recursive recursive Fighting_ silver study ah but level 4
- 递归递推之递归的函数
- M²BEV: Multi-Camera Joint 3D Detection and Segmentation with Unified Bird’s-Eye View Representation
猜你喜欢
随机推荐
[Advanced Digital IC Verification] Difference and focus analysis between SoC system verification and IP module verification
Loudi Center for Disease Control and Prevention Laboratory Design Concept Description
C# WPF image is displayed without problems, but the solution does not display the image at runtime
黑客入门,从HTB开始
[Study Notes] Persistence of Redis
YTU 2295: KMP模式匹配 一(串)
递归递推之Fighting_小银考呀考不过四级
跨域的五种解决方案
【黑马早报】雷军称低谷期曾想转行开酒吧;拜登正式签署芯片法案;软银二季度巨亏230亿美元;北京市消协约谈每日优鲜...
AtCoder初学者比赛077 D -小多
一种能让大型数据聚类快2000倍的方法,真不戳
BEVDet4D: Exploit Temporal Cues in Multi-camera 3D Object Detection 论文笔记
A can make large data clustering method of 2000 times faster, don't poke
Requirements for the construction of Loudi stem cell preparation laboratory
Fragment's show and hide
The recursive recursive Fighting_ silver study ah but level 4
R语言使用gt包和gtExtras包优雅地、漂亮地显示表格数据:gtExtras包的gt_highlight_rows函数高亮(highlight)表格中特定的数据行、配置高亮行的特定数据列数据加粗
教育Codeforces轮41(额定Div。2)大肠Tufurama
bgp双平面实验 路由策略控制流量
recursive recursive function









