/**
* @param {oject} obj
*/
function deepClone(obj) {
// obj 是 null ,或者不是对象和数组,直接返回
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 = {
name: 'dmhsq',
address: {
city: 'shanghai'
},
arr: ['a', 'b', 'c']
}
const obj2 = deepClone(obj1)
obj2.address.city = 'beijing'
console.log(obj1, obj2)