javascript深拷贝与浅拷贝
Opened this issue · 0 comments
minhuaF commented
javascript 数据类型
基本类型
Undefined, Null, String, Number, Boolean, Symbol
引用类型
Object, Array, Date, RegExp, Function
深拷贝
const deepClone = (source) => {
if (!source || typeof source !== 'object') {
throw new Error('error arguments')
}
// 判断类型时有的使用 `instanceof`, 这个和 `constructor ` 有什么不一样?
let targetObj = source.constructor === Array ? [] : {}
for (let 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
}