浅拷贝: 以赋值的形式拷贝引用的对象,仍指向同一个地址,修改原对象也会受到影响。
深拷贝:完全拷贝一个新对象,修改时原对象不再受到任何影响。
let obj = {
id: 1,
name: 'andy',
address:{
city: 'beijing'
},
arr: [ 'a', 'b', 'c']
}
//浅拷贝
const obj2 = obj
obj2.address.city = 'shanghai'
console.log(obj.address.city) // shanghai
//深拷贝
function deepClone(obj = {}){
if(typeof obj !== 'object' || obj == null){
return obj // obj不是对象或数组,直接返回
}
let result
if(obj instanceof Array){
result = []
}else{
result = {}
}
for(let key in obj){
if(obj.hasOwnProperty(key)){
//保证key不是原型的属性
//递归!!!
result[key] = deepClone(obj[key]);
}
}
return result
}
本人是新手,如有错误请留言更正,谢谢各位小老师❀❀❀❀❀❀