当前位置:网站首页>Xiaobai makes a wave of deep copy and shallow copy
Xiaobai makes a wave of deep copy and shallow copy
2022-07-26 09:38:00 【Bean sprouts don't eat beans】
Copy : Just as the name suggests, it is replication , however , The difference between deep and shallow copies is whether the change of the third-party value of the copy will affect the original object .
Shallow copy
That is, the new object copies the values of non object attributes and references of object attributes in the existing object , Object properties are not copied to memory
for instance
obj ={name:‘dress’,{color:‘red’}} newObj Shallow copy obj, Copy name Value , When the new object name When there is a change , The original object ( That is to say obj) Of name No change ;color Is an object property , Only one copy of the same memory address , In the new object color Value changes , In the original object color The value of should also be changed .
Several ways to realize shallow copy :
- Shallow copy of the object :Object.assign(target,…source)
let myobj = {
name:'John',
age:19,
like:"listen",
dislike:'banana',
want:{
pet:"dog"
}
}
let leo = Object.assign({
},myobj);
// Shallow copy is only in the root attribute ( The first level of the object ) Created a new object , But if the value of the attribute is an object, only one copy of the same memory address will be copied
leo.name = "Lucy";
console.log(leo.name,myobj.name) // Lucy John The original object obj Of name Nothing has changed
leo.want.pet = 'cat'; //
console.log(leo.want.pet,myobj.want.pet) // cat cat The value of the object attribute in the original object has also changed
2. Shallow copy of the array :arr.slice(begin,end): Returns a new array of cuts , The original array remains the same
let myArr = ['a','d','Ga',{
name:"ad calcium "}]
let leoo = myArr.slice.call(myArr);
leoo[0] = "wa";
leoo[1] = "ha";
leoo[2] = 'ha';
leoo[3].name=" WOW! "
console.log(leoo[0],myArr[0]) // wa a
console.log(leoo,myArr) // ["wa", "ha", "ha", {name: " WOW! "}] (4) ["a", "d", "Ga", {name: " WOW! "}]
3. Implement shallow copy :Array.prototype.concat(): Merge >=2 An array , Don't change the original array , Returns a new array
let myArr = ["a", "d", "Ga", {
name: " WOW! "}]
let myArr2 = [{
age:19}]
let leo3 =myArr.concat(myArr2);
leo3[0] = " shallow ";
leo3[1] = " Torture ";
leo3[4].age=30;
console.log(leo3,myArr,myArr2) //[" shallow ", " Torture ", "Ga", {name: " It's a shallow copy "}, {age: 30}] ["a", "d", "Ga", {name: " It's a shallow copy "}] [{age: 30}]
4. Use the extension operator to realize shallow copy : …
let leo4 ={
...myobj};
leo4.age="30";
leo4.want.pet = "panda";
console.log(leo4,myobj)
Write a shallow copy : Realization principle ---- The new object copies the values of non object attributes and references of object attributes in the existing object . Object properties are not copied to memory
function _clone(source) {
let target = {
};
for(let key in source) {
if(Object.prototype.hasOwnProperty.call(source,key)) {
target[key] = source[key]
}
}
return target;
}
let Qcopy = _clone(myobj);
Qcopy.name = "slsk"
Qcopy.want.pet = "cat"
console.log(Qcopy,myobj) //{name: "slsk", age: 19, like: "listen", dislike: "banana", want: {pet: "cat"}}
// {name: "les", age: 19, like: "listen", dislike: "banana", want: {pet: "cat"}}
Deep copy
Copy variable values , For reference data , Recurse to the basic type and then copy . The object after deep copy is completely isolated from the original object They don't influence each other
In fact, it is the time of deep copy , The system will separately assign a memory address to the new object , At this time, the two objects involved in the deep copy have their own memory addresses , No matter how the other one changes , The rest will not be affected .
Implement deep copy :
1.JSON.parse(JSON.stringfy())— principle : Serialize an object into a JSON character string , Convert the content of the object into a string and save it on disk , Reuse JSON.parse() Deserialization will JSON String becomes a new object
let myobj = {
name:"lmy",
age:18
}
// Implement deep copy
function deepClone(obj) {
return JSON.parse(JSON.stringify(obj));
}
let deepData = deepClone(myobj);
deepData.name = "deep lmy"
console.log(deepData,myobj)
2. Using third party libraries , Such as lodash
Hand written deep copy : The core idea is recursion , Traversal array , object , Copy until there are basic data types inside
const isObject = obj => typeof obj === 'object' && obj != null; // This implementation is only for arrays and {}, because null Of typeof The type is also object, Special filtration
// Only aim at {} And the simple implementation of array
function cloneDeep(source) {
if(!isObject(source)) {
// If the parameter is not an object {} Or array returns directly
return source;
}
const target = Array.isArray(source) ?[]:{
}; // Create a new object , If the incoming value is an array ,target Is an empty array , Otherwise, it is an empty object
for(var key in source) {
// Traverse the incoming source, Copy
if(Object.prototype.hasOwnProperty.call(source,key)) {
// Determine whether the current attribute is its own attribute , The following explains why hasOwnProperty.call()
if(isObject(source[key])) {
// If the attribute value is an object
target[key] = cloneDeep(source[key]); // Enter recursive deep copy
}else {
target[key] = source[key]
}
}
}
return target
}
// Use
let sjc = cloneDeep(myobjj);
sjc.name="textsss"
console.log(sjc,myobjj)
In a nutshell The difference between deep and shallow copy is to see whether the change of the new object will affect the original object after copying , Shallow copy if it has influence . No deep copy .
Attach the big guy link :https://mp.weixin.qq.com/s/-fiuJMW_xVaYZxrAuH0TBg It's really detailed Strong push !!!
-------------------------------------------------------- Split line --------------------------------------------------------------------------------------------
hasOwnProperty: Determine whether it is the self owned attribute of the object
js, There are some keywords , such as L:undefined/nullif/else/Number/Date… The purpose of keyword is to give these variable names some special functions , You can't just use it , Play a protective role . In the deep copy code above hasOwnproperty.call()…
The reason lies in js No protection hasOwnProperty This property name , This means that developers can use the attribute name , Customize the attribute value
for example :
let objTes = {
name:'hasOwnPropertyText',
hasOwnProperty:function(){
// It can also be a string , Array .... Custom use
return " Custom use hasOwnProperty"
}
}
console.log(objTes.hasOwnProperty()) // Custom use hasOwnProperty
console.log(objTes.hasOwnProperty("name")) // Custom use hasOwnProperty
// It takes up... Here hasOwnProperty This property name , So I want to use hasOwnProperty It is not feasible to judge whether it is the own attribute of the object
// You need to use... On the prototype chain hasOwnProperty To determine whether it is self owned , Use as :hasownProperty.call()
Object.prototype.hasOwnProperty.call(objTes,"name") // true
边栏推荐
猜你喜欢
随机推荐
EOJ 2020 January race E-number transformation
The problem of accessing certsrv after configuring ADCs
V-for dynamically sets the SRC of img
IIS website configuration
[Online deadlock analysis] by index_ Deadlock event caused by merge
asp.net 使用redis缓存(二)
调用DLL开启线程的问题
MySql5.7.25源码安装记录
Custom password input box, no rounded corners
Global variables in DLL
C managed and unmanaged
tabbarController的使用
phpexcel导出emoji符号报错
Malloc failed to allocate space and did not return null
系统安装Serv-U后IIS出错提示:HRESULT:0x80070020
m进制数str转n进制数
keepalived 实现mysql自动故障切换
Fiddler packet capturing tool for mobile packet capturing
malloc分配空间失败,并且不返回null
2020-12-29