Shallow vs. deep copy
- Shallow copy: one copy only when the data type is the object (Object, Array), only the reference copy.
- Deep Copy: Copy multilayer complex data types, reallocating memory space.
Two methods to achieve shallow copy
- Use
for ... in
realization
var obj = {
name: 'marron',
age: 18,
msg: {
sex: "1"
}
}
var o = {};
for(let k in obj) {
o[k] = obj[k]
};
console.log(o);
- Use es6 provided
Object.assign
var obj = {
name: 'marron',
age: 18,
msg: {
sex: "1"
}
}
var o = {};
Object.assign(o, obj);
console.log(o);
The above objects achieved by obj
assigning O. However, o attributes in sex
operation. Operation is quoted.
That change o.msg.sex
attribute obj.msg.sex
properties will change.
o.msg.sex = 2;
console.log(obj.msg.sex); // 2
Implement deep copy
Obviously the above is not the result we need.
The core idea is to open up the memory space of complex data types assignment.
Try to use a recursive copy, ideas are as follows:
- Use
for...in
assignment - When the assignment is first determined whether the current attribute array
a instanceof Array
, if the array is an array according recursive manner. - In determining whether the current attribute object
a instanceof Object
- The remaining considered simple data types can be assigned directly ...
const deepCopy = (newobj, oldobj) => {
for(let k in oldobj) {
let item = oldobj[k];
if(item instanceof Array) {
newobj[k] = [];
deepCopy(newobj[k], oldobj[k])
} else if (item instanceof Object){
newobj[k] = {};
deepCopy(newobj[k], oldobj[k])
} else {
newobj[k] = item
}
}
}
- test:
let obj = {
id: 1,
name: 'marron',
msg: {
age: 18
}
}
let o = deepCopy(o, obj);
console.log(o);
o.msg.age = 20;
console.log(obj);