当前位置:网站首页>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);
边栏推荐
- How to query database configuration parameters in GBase 8c, such as datestyle
- Pod环境变量和initContainer
- Manual upgrade and optimization tutorial of Lsky Pro Enterprise Edition
- net stop/start mysql80 access denied
- navicat mysql 内存占用过高,被强制关闭
- Gethostbyname \ getaddrinfo DNS domain name IP address is not safe
- HoloView -- Tabular Datasets
- In the background of the GBase 8c database, what command is used to perform the master-slave switchover operation for the gtm and dn nodes
- 巧妙利用unbuffer实时写入
- network basic learning
猜你喜欢
随机推荐
杨辉三角(c语言实现)
TiDB的真实数据库数据是存在kv和还是pd上?
三子棋(C语言实现)
Leicester Weekly 304 6135. The longest ring in the picture Inward base ring tree
pytest interface automation testing framework | parametrize source code analysis
Manual upgrade and optimization tutorial of Lsky Pro Enterprise Edition
sqlserver怎么查询一张表中同人员的交叉日期
《时代》杂志:元宇宙时代将改变世界
【Untitled】
淘宝商品详情又见淘宝详情,升级高级版 API
UXDB如何返回当前数据库所有表的记录数?
MySQL query advanced - from the use of functions to table joins, do you remember?
【杭电多校第四场 B题】最短路图+缩点dp
最新的Cesium和Three的整合方法(附完整代码)
笔记。。。。
ogg同步oracle到mysql,字段里面可能有需要转义的字符,怎么配置转义?
SkiaSharp 之 WPF 自绘 五环弹动球(案例版)
Delphi MDI appliction documents maximize display, remove buttons such as maximize and minimize
常见的API安全缺陷有哪些?
sql server, FULL模式, dbcc shrinkfile(2,1) 不能收缩事务日志,还是原来的大小,是为什么?