深拷贝浅谈
1.通过序列化和反序列化实现的深拷贝方式(不建议使用)
//普通对象
let obj = {a:"str1"};
console.log(JSON.parse(JSON.stringify(obj)));//{a:"str1"}
//Map
let obj = {b: new Map([
[1, 'one'],
[2, 'two'],
[3, 'three'],
])};
console.log(JSON.parse(JSON.stringify(obj)));//[b:[1, 'one'],[2, 'two'],[3, 'three'],
]
2.递归实现深拷贝
[
function deepClone(obj = {}) {
if (typeof obj !== 'object' || obj == null) {
// obj 是 null ,或者不是对象和数组,直接返回
return obj
}
// 初始化返回结果
let result
if (obj instanceof Array) {
result = []
} else {
result = {}
}
for (let key in obj) {
// 保证 key 不是原型的属性
if (obj.hasOwnProperty(key)) {
// 递归调用!!!
result[key] = deepClone(obj[key])
}
}
// 返回结果
return result
}