一行实现深拷贝数组
const deepCopyArr = arr => arr.reduce((acc, cur) => (
cur instanceof Array ? [...acc, deepCopyArr(cur)] : [...acc, cur]
), [])
一行实现深拷贝对象
const deepCopyObj = obj => Object.entries(obj).reduce((acc, [key, value]) => (
typeof value === 'object' ? { ...acc, [key]: deepCopyFun(value) } : { ...acc, [key]: value }
), {})
通用方法
const deepCopy = obj => {
if (typeof obj !== 'object') return
const newObj = obj instanceof Array ? [] : {}
for (const key in obj) {
if (obj.hasOwnProperty(key)) {
newObj[key] = typeof obj[key] === 'object' ? deepCopy(obj[key]) : obj[key]
}
}
return newObj
}
技巧性方法
// 不足之处是不能拷贝函数
const deepCopy = obj => JSON.parse(JSON.stringi