当前位置:网站首页>How to implement deep copy in js?
How to implement deep copy in js?
2022-08-01 09:26:00 【Confused】
How to implement deep copy and shallow copy?
1. What is deep copy and shallow copy?
Link: The difference between shallow copy, deep copy and assignment in js
2. Implementation of deep copy
Deep copy is for reference data type
Method 1: Implemented through ES6's new spread operator (…)
Code Sample
let arr = [1, 2, 5, 3, 7, 4];// make a deep copylet newArr = [...arr];console.log('deep copy new array', newArr);//Modify the value of the element in the new arraynewArr[3] = 273287;console.log('New array after modified value', newArr);console.log('original array', arr);//The value in the original array has not been modified
Run Results
Method 2: Implemented by JSON object
Convert the object to a string through JSON.stringify(), and convert the string to a JSON object through JSON.parse(), which will become a new object at this time
Disadvantages of this method: Cannot copy the function inside the object
Code Sample
let obj = {name: 'Zhang San',address: {sheng: "Sichuan",shi: "Chengdu"},sex: "male",fun: () => {console.log(obj.name);}}console.log('original obj',obj);//Convert obj to string via JSON.stringify()let str=JSON.stringify(obj);// Then convert the string to JSON object through JSON.parse()let newObj=JSON.parse(str);console.log('new newObj', newObj);//The function in obj is not copied//modify the value of the new objectnewObj.name='Li Si';console.log('New object after modifying the property value', newObj);console.log('The original object after modifying the property value of the new object', obj);//No change
Run Results
Method 3: use recursive method to achieve
Code example:
function deepClone(obj) {// Determine if the passed parameter is an arraylet objClone = Array.isArray(obj) ? [] : {};if (obj && typeof obj === 'object') {for (let key in obj) {if (obj.hasOwnProperty(key)) {// Determine whether the obj sub-element is an object, if so, copy recursivelyif (obj[key] && typeof obj[key] === 'object') {objClone[key] = deepClone(obj[key]);} else {objClone[key] = obj[key];}}}}return objClone;}let a=[1,2,3,4,{name:"Zhang Shan",age:18}];let b=deepClone(a);console.log('Original array a',a);console.log('New array b' after deep copy,b);// modify the value of the original arraya[3]=99999;a[4].age=34567console.log('The original array a after modifying the element value of the original array',a);console.log('The new array b',b) after modifying the value of the original array elements;
Run Results
Method 4: Implemented through the extend method in jquery
let arr = [1, 3, 5, 7];let newArr = $.extend(true, [], arr);//true is a deep copy, false is a shallow copynewArr.push(999)console.log('newArr',newArr);console.log('arr',arr);
边栏推荐
- leetcode-6133:分组的最大数量
- Microsoft Azure & NVIDIA IoT 开发者季 I|Azure IoT & NVIDIA Jetson 开发基础
- rpm和yum
- [Tear AHB-APB Bridge by hand]~ Why aren't the lower two bits of the AHB address bus used to represent the address?
- 指针的介绍及应用
- STM32个人笔记-嵌入式C语言优化
- Explain / Desc 执行计划分析
- ASP.NET Core 6框架揭秘实例演示[30]:利用路由开发REST API
- Graduation thesis writing skills
- HoloView -- Tabular Datasets
猜你喜欢
Intensive reading of ACmix papers, and analysis of its model structure
会议OA(待开会议&所有会议)
leetcode-6134:找到离给定两个节点最近的节点
Redis 3.2.3 crashed by signal: 11 服务宕机问题排查
How to ensure the consistency of database and cache data?
Leicester Weekly 304 6135. The longest ring in the picture Inward base ring tree
Get the Token from the revised version of Qubutu Bed
网络个各种协议
HoloView 在 jyputer lab/notebook 不显示总结
Comprehensive experiment BGP
随机推荐
WLAN networking experiment of AC and thin AP
笔记。。。。
Introduction to ADAS
Pod环境变量和initContainer
SkiaSharp's WPF self-painted five-ring bouncing ball (case version)
SaaS安全认证综合指南
Comprehensive experiment BGP
YOLOv7-Pose尝鲜,基于YOLOv7的关键点模型测评
安装GBase 8c数据库的时候,报错显示“Resource,如何解决?
Mysql数据库的部署以及初始化步骤
The soul asks: How does MySQL solve phantom reads?
XX市消防救援指挥中心实战指挥平台多链路聚合解决方案实例
notes....
2022杭电中超杯(1)个人题解
18张图,直观理解神经网络、流形和拓扑
【无标题】
力扣周赛304 6135. 图中的最长环 内向基环树
HoloView -- Tabular Datasets
Leetcode - 6135: the longest part of the figure
179. 最大数