当前位置:网站首页>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
边栏推荐
猜你喜欢
小程序纪录
一种分布式深度学习编程新范式:Global Tensor
R language ggplot2 visualization: align the legend title to the middle of the legend box in ggplot2 (default left alignment, align legend title to middle of legend)
Fiddler抓包工具之移动端抓包
docker配置mysql集群
After attaching to the process, the breakpoint displays "currently will not hit the breakpoint, and no symbols have been loaded for this document"
Windows下Redis哨兵模式搭建
asp. Net using redis cache
Gauss elimination solves the inverse of matrix (Gauss)
【Mysql数据库】mysql基本操作集锦-看得会的基础(增删改查)
随机推荐
CSV data file settings of JMeter configuration components
JS判断数据类型 Object.prototype.toString.call和typeof
高斯消元求解异或线性方程组
Basic use of Arc GIS 2
配置ADCS后访问certsrv的问题
简单行人重识别代码到88%准确率 郑哲东 准备工作
Simple pedestrian recognition code to 88% accuracy Zheng Zhedong preparation
附加到进程之后,断点显示“当前不会命中断点 还没有为该文档加载任何符号”
Mo team learning summary (II)
[MySQL] understand the important architecture of MySQL (I)
电机转速模糊pid控制
QT随手笔记(六)——更新界面、截图、文件对话框
R language ggpubr package ggsummarystats function visualizes the grouping box diagram (custom grouping color) and adds the statistical values corresponding to the grouping under the x-axis label (samp
Wechat applet avatarcropper avatar clipping
面试突击68:为什么 TCP 需要 3 次握手?
dll中的全局变量
MFC handy notes
Android implements the caching mechanism and caches multiple data types
Does volatile rely on the MESI protocol to solve the visibility problem? (top)
phpexcel导出emoji符号报错