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)

**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。