当前位置:网站首页>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);
边栏推荐
- 《时代》杂志:元宇宙时代将改变世界
- Ogg synchronizes oracle to mysql, there may be characters that need to be escaped in the field, how to configure escape?
- 【杭电多校第四场 B题】最短路图+缩点dp
- Idea common plugins
- Introduction to ADAS
- 会议OA(待开会议&所有会议)
- 力扣周赛304 6135. 图中的最长环 内向基环树
- navicat mysql 内存占用过高,被强制关闭
- Holoview--Introduction
- C语言中编译时出现警告C4013(C语言不加函数原型产生的潜在错误)
猜你喜欢
随机推荐
navicat mysql 内存占用过高,被强制关闭
Holoview--Introduction
pytest interface automation testing framework | parametrize source code analysis
Detailed explanation of JVM runtime data area and JMM memory model
HoloView--Customization
Node's traditional and advanced practices for formatting time (moment)
Is the real database data of TiDB stored in kv and pd?
Redis 3.2.3 crashed by signal: 11 服务宕机问题排查
Explain / Desc execution plan analysis
AC与瘦AP的WLAN组网实验
What do the values 1, 2, and 3 in nodetype mean?
HPC系统简介
STM32个人笔记-程序跑飞
Explain / Desc 执行计划分析
sqlserver怎么查询一张表中同人员的交叉日期
扁平数组转树结构实现方式
【杭电多校第四场 B题】最短路图+缩点dp
Graduation thesis writing skills
various network protocols
Mysql数据库的部署以及初始化步骤








