function cloneDeep(source, hash = new WeakMap()) {
if (!isObject(source)) return source
const root = Array.isArray(source) ? [] : {}
const loopList = [
{
parent: root,
key: undefined,
data: source
}
]
while(loopList.length) {
const { parent, key, data } = loopList.pop()
let target = parent
if (key !== undefined) {
target = parent[key] = Array.isArray(data) ? [] : {}
}
if (hash.has(data)) {
target = hash.get(data)
continue
}
hash.set(data, target)
for (let k in data) {
if (Object.prototype.hasOwnProperty.call(data, k)) {
if (isObject(data[k])) {
loopList.push({
parent: target,
key: k,
data: data[k]
})
} else {
target[k] = data[k]
}
}
}
}
return root
// 判断是否对象类型
function isObject(source) {
return typeof source === 'object' && source !== null
}
}
const data = {
a: {
b: {
c: 1,
d: [
{c: 2},
'ss'
]
}
}
}
const clone = cloneDeep(data)
console.log(clone)
console