function deepClone(obj = {}) {
// obj是null或undefined(留神这里应用的==不是===)或者不是对象和数组,间接返回
if (typeof obj !== 'object' || 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
}
// 测试
const obj1 = {
age: 20,
name: '张三',
addresss: {
city: 'beijing'
},
arr: ['a', 'b', 'c']
}
const obj2 = deepClone(obj1)
obj2.name = '李四'
obj2.addresss.city = 'hefei'
obj1.arr[0] = 100
console.log(obj1, obj2)
发表回复