//测试对象
var test = {
a1: 'name',
a2: undefined,
a3: null,
arr: [111, { age: 18 }],
info: {
uname: 'zs'
}
}
//实现深拷贝的函数
function deepCopy(source) {
if (typeof source !== 'object') return source
//判断是对象还是数组
let res = source.constructor === Array ? [] : {}
for (var key in source) {
// hasOwnProperty 这个方法会查找一个对象是否有某个属性,但是不会去查找它的原型链。
if (source.hasOwnProperty(key)) {
//考虑对象属性可能是 undefined 和 null 的情况
if (source[key]) {
if (source[key].constructor === Object) {
res[key] = deepCopy(source[key])
} else {
res[key] = source[key]
}
} else {
res[key] = source[key]
}
}
}
return res
}
console.log(deepCopy(test));