const obj = {
a: 1,
name: 'xx',
address: {
city: 'beijing'
},
arr: ['a', 'b']
}
function cloneDeep(obj) {
// 不是对象或者数组 直接返回
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] = cloneDeep(obj[key])
}
}
return result
}