当前位置:网站首页>实现一个深克隆
实现一个深克隆
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 互不影响, 这个样子就是 简单版的深克隆就写好了
边栏推荐
- Ethernet channel Ethernet channel
- MySQL面试题整理
- 大佬们有遇到过这个问题吗? MySQL 2.2 和 2.3-SNAPSHOT 都这样,貌似是
- 2022-08-09:以下go语言代码输出什么?A:否,会 panic;B:是,能正确运行;C:不清楚,看投票结果。 package main import ( “fmt“ “syn
- 学习日记9
- C# WPF image is displayed without problems, but the solution does not display the image at runtime
- 2022-08-09: What does the following go code output?A: No, it will panic; B: Yes, it can run correctly; C: Not sure, see the voting result.package main import (“fmt“ “syn
- BEVDet4D: Exploit Temporal Cues in Multi-camera 3D Object Detection 论文笔记
- 机器学习实战(2)——端到端的机器学习项目
- tampercfg内核模块导致机器频繁crash
猜你喜欢

Guidelines for Sending Overseas Mail (2)

LeetCode·每日一题·640.求解方程·模拟构造

Stream通过findFirst()查找满足条件的一条数据

Solution for "Certificate not valid for requested usage" after Digicert EV certificate signing

M²BEV: Multi-Camera Joint 3D Detection and Segmentation with Unified Bird’s-Eye View Representation

神了!阿里数据库专家纯手写了这份604页的Oracle+MySQL攻坚指南

进程和计划任务管理

Interface Automation Testing Basics

Blast!ByteDance successfully landed, only because the interview questions of LeetCode algorithm were exhausted

Jenkins修改默认主目录
随机推荐
Jenkins修改默认主目录
CodeForces - 834C
OpenStack-related commands that need to be recorded _ self-use
SenseTime self-developed robotic arm, the first product is an AI chess-playing robot: Guo Jingjing is also invited as an endorsement
一种能让大型数据聚类快2000倍的方法,真不戳
LeetCode medium topic search of two-dimensional matrix
MYSQL误删数据恢复
Matrix Keyboard & Calculator Small Project Based on 51 (UcosII)
kubernetes介绍
Ethernet channel Ethernet channel
I would like to ask the big guys, how to solve this error when cdc oracle initializes a 3 million table task running
ABAP 里文件操作涉及到中文字符集的问题和解决方案试读版
Basic knowledge of switches
Shell:数组
瑞幸「翻身」?恐言之尚早
[Advanced Digital IC Verification] Difference and focus analysis between SoC system verification and IP module verification
rpn:def concat_box_prediction_layers
tampercfg内核模块导致机器频繁crash
C# InitializeComponent() does not exist in the current context
交换机的基础知识