浅拷贝: 只拷贝一层, 对更深层次对象只拷贝了地址
深拷贝: 层层拷贝, 对每一层级的数据都进行拷贝
实现浅拷贝的方法:
方法一:
let obj = {
id: 1,
name: 'Andy',
msg: {
age: 18
}
}
let newObj = {};
for (const key in obj) {
newObj[key] = obj[key];
}
obj.msg.age = 19;
console.log('====================================');
console.log('newObj', newObj, 'obj', obj);
console.log('====================================');
方法二:
let newObj = {};
Object.assign(newObj, obj);
obj.msg.age = 19;
console.log('====================================');
console.log('newwObj', newObj, 'obj', obj);
console.log('====================================');
方法三:
let newObj = {...obj};
obj.msg.age = 20;
console.log('====================================');
console.log('newObj', newObj, 'obj', obj);
console.log('====================================');
方法四:
let newObj = obj;
obj.msg.age = 20;
console.log('====================================');
console.log('浅拷贝', 'newObj', newObj, 'obj', obj, newObj === obj);
console.log('====================================');
实现深拷贝的方法:
let obj = {
id: 1,
name: 'Andy',
msg: {
age: 18
},
likeAuthor: ['刘同', '张嘉佳']
}
let newObj = {};
function deepCopy(newObj, obj) {
for (const key in obj) {
if(obj[key] instanceof Array) {
newObj[key] = [];
deepCopy(newObj[key], obj[key])
}else if(obj[key] instanceof Object) {
newObj[key] = {};
deepCopy(newObj[key], obj[key])
}else {
newObj[key] = obj[key];
}
}
}
deepCopy(newObj, obj);
obj.msg.age = 20
console.log('====================================');
console.log('newObj', newObj, 'obj', obj);
console.log('====================================');