vuex中有一个工具类有如下处理深拷贝代码:
function deepCopy(obj, cache = []) {
// just return if obj is immutable value
if (obj === null || typeof obj !== 'object') {
return obj
}
// if obj is hit, it is in circular structure
const hit = cache.filter(c => c.original === obj)[0]
if (hit) {
return hit.copy
}
const copy = Array.isArray(obj) ? [] : {}
// put the copy into cache at first
// because we want to refer it in recursive deepCopy
cache.push({
original: obj,
copy
})
Object.keys(obj).forEach(key => {
copy[key] = deepCopy(obj[key], cache)
})
return copy
}
使用这个函数copy对象的时候,如果对象中某个属性的值是date类型的话,它会把date类型转成一个空对象:
let obj = {
obj: new Date()
}
console.log(obj)
console.log(deepCopy(obj))
请问为什么会这样?怎么修改代码能修复这个问题?
这个工具类明显是简化后的,可能是人家自己自用的。少考虑了n种情况,自己写一个,或者直接用lodash的cloneDeep吧