当前位置:网站首页>实现一个深克隆
实现一个深克隆
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 互不影响, 这个样子就是 简单版的深克隆就写好了
边栏推荐
- YTU 2295: KMP模式匹配 一(串)
- Network Saboteur
- C# WPF image is displayed without problems, but the solution does not display the image at runtime
- 神经网络可视化有3D版本了,美到沦陷!(已开源)
- 表中存在多个索引问题? - 聚集索引,回表,覆盖索引
- 黑客入门,从HTB开始
- 一种能让大型数据聚类快2000倍的方法,真不戳
- 浙大、阿里提出DictBERT,字典描述知识增强的预训练语言模型
- Wirshark common operations and tcp three-way handshake process example analysis
- 生成树协议STP(Spanning Tree Protocol)
猜你喜欢
随机推荐
日志@Slf4j介绍使用及配置等级
Overview of Loudi Petrochemical Experiment Design and Construction Planning
How to describe multiple paragraphs with different font settings in Open Office XML format
高数_证明_弧微分公式
I would like to ask the big guys, how to solve this error when cdc oracle initializes a 3 million table task running
Have you guys encountered this problem?MySQL 2.2 and 2.3-SNAPSHOT are like this, it seems to be
Code Casual Recording Notes_Dynamic Programming_70 Climbing Stairs
高数_证明_曲率公式
进程和计划任务管理
C#WPF 图片在显示时没有问题,但在运行时图片显示不出来的解决
ArcMAP has a problem of -15 and cannot be accessed [Provide your license server administrator with the following information:Err-15]
X5WebView使用
malloc 函数详解
MySQL面试题整理
递归递推之计算组合数
【百度统计】用户行为分析
R语言使用gt包和gtExtras包优雅地、漂亮地显示表格数据:gtExtras包的gt_highlight_rows函数高亮(highlight)表格中特定的数据行、配置高亮行的特定数据列数据加粗
3DS MAX 批量导出文件脚本 MAXScript 带界面
【MinIO】工具类使用
【量化交易行情不够快?】一文搞定通过Win10 wsl2 +Ubuntu+redis+pickle实现股票行情极速读写