js入门之手写深拷贝-爱代码爱编程
简单写个深拷贝
let deepClone = function(source) {
// targetObj: 目标对象
const targetObj = source.constructor === Array ? [] : {}
for (let key in source) {
if (source.hasOwnProperty(key)) {
// 判断是不是本身的key
if (source[key] && typeof source[key] === 'object') {
// 如果source[key]是对象||数组, 递归
targetObj[key] = deepClone(source[key])
} else {
targetObj[key] = source[key]
}
}
}
return targetObj
}
const obj = {
name: 'a',
class: [
'title',
'data',
['mate']
],
ob: {
age: 15,
list: [1, 2, 3],
new: {
date: '20230203'
}
}
}
const obj2 = deepClone(obj)
obj2.class.push('4')
obj.class[2].push('5')
obj2.ob.age = 18
obj.ob.list.push('323232')
console.log('obj2 => ', obj2, 'obj => ', obj)
输出结果如下,深拷贝成功