// 检查类型
const checkType = data => {
return Object.prototype.toString.call(data).slice(8, -1)
}
const deepClone = target => {
const targetType = checkType(target)
let result = null
if (targetType === 'Object') {
result = {}
} else if (targetType === 'Array') {
result = []
} else {
return target
}
for (const key in target) {
let value = target[key]
const valueType = checkType(value)
if (['Array', 'Object'].includes(valueType)) {
result[key] = deepClone(value)
} else {
result[key] = value
}
}
return result
}
JS深拷贝
深度克隆与类型判断:JavaScript对象与数组复制技巧
最新推荐文章于 2025-04-29 07:00:00 发布
本文介绍了一种JavaScript函数,用于检测数据类型并实现深拷贝。checkType 函数用于确定输入数据是对象、数组还是基本类型,而 deepClone 函数则根据类型递归地创建副本,确保复杂数据结构的完整复制。

1万+

被折叠的 条评论
为什么被折叠?



