话不多说,直接上代码
<!--工具函数-->
const _toString = Object.prototype.toString
function getType(obj) {
return _toString.call(obj).slice(8, -1)
}
<!--深度优先-->
function DFSDeepClone(obj, vistied = new Set(), level = 0) {
let res = {}
if (getType(obj) === 'Object' || getType(obj) === 'Array') {
if (vistied.has(obj)) {
// 处理环状结构
res = obj
} else {
vistied[level] = obj
vistied.add(obj)
res = getType(obj) === 'Object' ? {} : []
Object.keys(obj).forEach(k => {
res[k] = DFSDeepClone(obj[k], vistied, level + 1)
})
}
} else if (typeof obj === 'function') {
res = eval(`(${obj.toString()})`)
} else {
res = obj
}
return res
}
<!--广度优先-->
function BFSDeepClone(obj) {
if (getType(obj) !== 'Object'