当前位置:网站首页>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 modifiedRun 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 changeRun 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);
边栏推荐
- 【STM32】入门(二):跑马灯-GPIO端口输出控制
- Comprehensive experiment BGP
- pytest interface automation testing framework | parametrize source code analysis
- 巧妙利用unbuffer实时写入
- HPC系统简介
- Idea 常用插件
- 【STM32】入门(一):环境搭建、编译、下载、运行
- leetcode-6133:分组的最大数量
- Optimal dazzle Oracle database support what kinds of type of the time and date
- ASP.NET Core 6框架揭秘实例演示[30]:利用路由开发REST API
猜你喜欢
随机推荐
HoloView 在 jyputer lab/notebook 不显示总结
notes....
毕业论文写作技巧
Microsoft Azure & NVIDIA IoT 开发者季 I|Azure IoT & NVIDIA Jetson 开发基础
Microsoft Azure & NVIDIA IoT developers season I | Azure IoT & NVIDIA Jetson development foundation
Ogg synchronizes oracle to mysql, there may be characters that need to be escaped in the field, how to configure escape?
Leetcode - 6135: the longest part of the figure
高级驾驶辅助系统ADAS简介
[Beyond programming] When the fig leaf is lifted, when people begin to accept everything
杨辉三角(c语言实现)
How to query database configuration parameters in GBase 8c, such as datestyle
热修复技术可谓是百花齐放
优炫数据库支持Oracle哪几种时间及日期类型
Change Servlet project to SSM project
Classify GBase 8 s lock
[Dataset] Dataset summary of various insulators, bird's nests and anti-vibration hammers
CTO强烈禁止使用Calendar,那用啥?
HoloView -- Tabular Datasets
Explain / Desc 执行计划分析
A problem with writing to the database after PHP gets the timestamp





![[Beyond programming] When the fig leaf is lifted, when people begin to accept everything](/img/e1/ff8d416c99e1f370d73b9520654ddf.jpg)



