// 手写深拷贝
function deepClone(source) {
// 1.判断传入的值是 Array 还是 Object
const targetObj = source.constructor === Array ? [] : {}
for (const key in source) {
if (source.hasOwnProperty(key)) {
if (source[key] && typeof source[key] === 'object') {
// 引用数据类型
targetObj[key] = source[key].constructor === Array ? [] : {}
targetObj[key] = deepClone(source[key])
} else {
// 基本数据类型
targetObj[key] = source[key]
}
}
}
return targetObj
}
let obj = {
name: '张三',
age: 18,
student: [{name: '小明'}],
}
let newObj = obj
newObj.name = "李四"
newObj.student = {}
console.log(obj===newObj); // true
网友评论