当前位置:网站首页>Deep copy and shallow copy
Deep copy and shallow copy
2022-07-19 01:35:00 【Hemubai】
List of articles
One 、 Basic data and reference data types
Two 、 How to realize deep copy ?
1. adopt JSON.stringify() and JSON.parse()
2. Recursively traverse the bottom layer for deep copy
3. adopt jq Of extend Method to make a deep copy
4. Only the first layer of the object can be deeply copied
About JSON.parse(JSON.stringify()) Supplement of deep copy .
Preface
How to distinguish between deep copy and shallow copy ?
let a = [0,1,2,3,4]
let b = a;
console.log(b); //[0,1,2,3,4]
a[0] =1;
console.log(b); //[1,1, 2, 3, 4] According to the example above ,b Copy the a, When we modify a When ,b The value of also changed , This is a shallow copy . If we modify a after ,b There is no change , Then it is a deep copy .
One 、 Basic data and reference data types
Why did we modify a,b It will also change ?
That involves the concepts of basic data type and reference data type .
Basic data type :number,string,boolean,null,underfined,symbol as well as es10 Newly added BigInt.
Reference data type :object,array,function etc. .
- The basic data type name and value are stored in the stack .
for example :let a = 1; b = a;
a= 1 The memory will be opened in the stack memory to store the corresponding name and value .
b = a The time stack memory will open up a new memory , Deposit b Value , Two variables have their own spatial complementary interference , So we modify b when a It won't be affected . although b Not subject to a influence , But it's not a deep copy , Because the deep copy itself is only for the more complex object Type data .
- Reference data type -- Name and address pointers are in stack memory , Value in heap memory .

When obj1 = obj Copy , In fact, it is to open up memory in the stack to store obj1, The corresponding values are the same obj The corresponding address pointer .
That is to say obj1 And obj Point to the same value in the heap memory .

When we are right obj[0] = 1 When modifying an array , because obj And obj1 Point to the same address , So nature obj1 It's also affected , This is what we call a shallow copy .

Two 、 How to realize deep copy ?
1. adopt JSON.stringify() and JSON.parse()

As can be seen from the figure above ,obj adopt JSON.parse(JSON.stringify()) to obj1 After the assignment , change obj Medium attribute value ,obj1 It didn't change with it , Deep copy is realized .
however , This method is also defective Of :
let a={
name:' Little ',
age:20,
num:undefined,
no:Symbol(1),
info:function(){return {address:' hebei ',iphone:'1234567'}}
}
let b = JSON.parse(JSON.stringify(a));
b //{name: " Little ", age: 20}
a //{name: " Smile ", age: 20, num: undefined, no: Symbol(1), info: ƒ}As can be seen above , JSON.parse(JSON.stringify()) Can't copy function,undefined and symbol, It also cannot solve the circular reference object , Will cause data loss .
2. Recursively traverse the bottom layer for deep copy
let obj={
name:' Little ',
age:20,
num:undefined,
no:Symbol(1),
new:{name:'title',id:[2,[3,4]]},
info:function(){return {address:' hebei ',iphone:'1234567'}}
}
const clone = (obj)=>{
let data= typeof obj === 'object' ? {}:[];
if(obj && typeof obj ==='object'){
for(let key in obj){
if(obj[key] && typeof obj[key]==='object'){
data[key] = clone(obj[key])
}else{
data[key] = obj[key]
}
}
}
return data;
}
let obj2 = clone(obj);
obj.new.name='value';
obj.new.id[1][0]=10;
console.log(obj2);
console.log(obj);
3. adopt jq Of extend Method to make a deep copy
$.extend( [deep ], target, object1 [, objectN ] )
deep Indicates whether there is a deep copy , by true Is a deep copy , by false, Is a shallow copy
target Object type Target audience , Member properties of other objects will be attached to the object .
object1 objectN Optional . Object type The first one and the first one N Two merged objects .
let a={
name:' Little ',
age:20,
num:undefined,
no:Symbol(1),
new:{name:'title',id:[2,[3,4]]},
info:function(){return {address:' hebei ',iphone:'1234567'}}
}
b=$.extend(true,[],a);
a.name=" Smile ";
a.new.name="value";
a.new.id[1][0] = 10;
console.log(a,b); 
4. Only the first layer of the object can be deeply copied
- Object.assign() Merge of objects
- Array.slice() Method
- Array.concat() Method
- es6 Deconstruct assignment
Only the first layer of the object can be deeply copied , If the properties in the object are also objects , There is no way to make a deep copy .
About JSON.parse(JSON.stringify()) Supplement of deep copy .
- obj There are new Date(), After deep copy , Time will become a string . Not the time object ;
- obj Are there in RegExp、Error object , The result of serialization will become an empty object {};
const a ={
name:'a',
date:new RegExp('\\w+'),
};
const b =JSON.parse(JSON.stringify(a));
a.name ='test'
console.log( a, b)- obj Are there in NaN、Infinity and -Infinity, The result of serialization will be nul.
const a ={
name:'a',
date:NaN,
};
const b =JSON.parse(JSON.stringify(a));
a.name ='test'
console.log(a, b)边栏推荐
猜你喜欢

量化行业知识汇总

Text indent in uniapp doesn't work, and the indentation in the first line of uniapp doesn't work. How to solve it?

mock平台的使用说明

Win10 vscode 代码格式化设置与远程断点调试

wget 警告: 无法验证

uni-app微信小程序——商城(7)——商品详情

XXX packages are looking for funding run `npm fund` for details解决方法

object-fit:cover;在小程序中不起作用,小程序图片变形了如何处理
![[GFCTF 2021]Baby_ Cve-2021-41773 on the web](/img/e0/7541860509b3b77f758447e377f2f7.png)
[GFCTF 2021]Baby_ Cve-2021-41773 on the web

MoveIt2——2.MoveIt在RViz中的快速入门
随机推荐
[GFCTF 2021]Baby_ Cve-2021-41773 on the web
替换URL中的特殊字符(%E2%80%8B)
07_事件的基本使用
JS string to object JS object to string JS string to object
JSX syntax
mock平台的使用说明
Use bat to automatically execute CMD commands (multiple commands or a single command)
es6语法--解构赋值
js替换字符串某个字符,js修改字符串中指定字符
elemtnui 表格如何修改某行文字颜色(elemtnui table 修改某行文字颜色)
(五)printf(代替echo)
[elementui El date picker date selector, the end time must not be earlier than the start time, and only the date of the specified number of days from the start time can be selected]
(6) Test command
Vue项目部署,清理缓存
es可选链
three.js初体验:模拟一个小树杈的生长
uni-app微信公众号(4)——地址管理页面
Solve the flashing of the menu switch at the bottom of applet customization
[SWPU 2019] network TTL encryption and some related knowledge
uni-app微信小程序——商城(8)——订单详情