当前位置:网站首页>实现一个深克隆
实现一个深克隆
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 互不影响, 这个样子就是 简单版的深克隆就写好了
边栏推荐
- 神经网络可视化有3D版本了,美到沦陷!(已开源)
- 数据产品经理那点事儿 二
- 【黑马早报】雷军称低谷期曾想转行开酒吧;拜登正式签署芯片法案;软银二季度巨亏230亿美元;北京市消协约谈每日优鲜...
- 【iOS】Organization of interviews
- Network Saboteur
- Blast!ByteDance successfully landed, only because the interview questions of LeetCode algorithm were exhausted
- Fragment的show和hide
- 【JS高级】ES5标准规范之创建子对象以及替换this_10
- Interface Automation Testing Basics
- [Study Notes] Persistence of Redis
猜你喜欢
【JS高级】ES5标准规范之创建子对象以及替换this_10
AWS 安全基础知识
瑞幸「翻身」?恐言之尚早
Blast!ByteDance successfully landed, only because the interview questions of LeetCode algorithm were exhausted
LeetCode·297.二叉树的序列化与反序列化·DFS·BFS
SenseTime self-developed robotic arm, the first product is an AI chess-playing robot: Guo Jingjing is also invited as an endorsement
日志@Slf4j介绍使用及配置等级
Shell:数组
高数_证明_弧微分公式
Merge similar items in LeetCode simple questions
随机推荐
黑客入门,从HTB开始
[target detection] small script: extract training set images and labels and update the index
Matlab画分段函数「建议收藏」
C#报错 The ‘xmins‘ attribute is not supported in this context
22!Beijing Changping District notified catering service enterprises with food safety problems
YTU 2295: KMP pattern match one (string)
C#WPF 图片在显示时没有问题,但在运行时图片显示不出来的解决
A detailed explanation of implementation api embed
递归递推之递归的函数
3DS MAX batch export file script MAXScript with interface
【目标检测】小脚本:提取训练集图片与标签并更新索引
生成树协议STP(Spanning Tree Protocol)
神了!阿里数据库专家纯手写了这份604页的Oracle+MySQL攻坚指南
【MinIO】工具类使用
C# 当前上下文中不存在InitializeComponent()
【百度统计】用户行为分析
神经网络可视化有3D版本了,美到沦陷!(已开源)
高数_证明_弧微分公式
22家!北京昌平区通报存在食品安全问题餐饮服务企业
LeetCode medium topic search of two-dimensional matrix