function deepClone(obj) {
if (!obj || typeof obj !== 'object') {
return obj
}
let result = Array.isArray(obj) ? [] : {}
for (let key in obj) {
if (obj.hasOwnProperty(key)) {
if (obj[key] && typeof obj[key] === 'object') {
result[key] = deepClone(obj[key])
} else {
result[key] = obj[key]
}
}
}
return result
}
调用方式为 obj.deepClone()
function deepClone() {
if (this && typeof this !== 'object' || Object.keys(this).length !== 0) {
return this
}
let toString = Object.prototype.toString
let result = determine(this) == 'Array' ? [] : {}
for (key in this) {
if (this.hasOwnProperty(key)) {
if (this[key] && determine(this[key]) == 'Object' || determine(this[key]) == 'Array') {
result[key] = this[key].deepClone()
} else {
result[key] = this[key]
}
}
}
function determine(str) {
return toString.call(str).split(' ')[1].split(']')[0]
}
return result
}
深拷贝,防止递归引用栈溢出
function deepClone(obj, hash = new Map()) {
// obj值为null或undefind
if (obj == null) return obj
// 如果值不为对象就返回
if (obj instanceof RegExp) return new RegExp(obj)
if (obj instanceof Date) return new Date(obj)
if (typeof obj != 'object') return obj
if (hash.has(obj)) return hash.get(obj)
let newObj = new obj.constructor
hash.set(obj, newObj)
for (let key in obj) {
if (obj.hasOwnProperty(key)) {
newObj[key] = deepClone(obj[key], hash)
}
}
return newObj
}