<script>
const data = {
name: 'cp',
age: 20,
list: [{
height: 180
}],
info: {
msg: '123'
}
}
function deepCopy(source) {
if (!isObject(source)) return source //如果不是对象的话直接返回
let target = Array.isArray(source) ? [] : {} //数组兼容
for (let k in source) {
if (source.hasOwnProperty(k)) {
if (typeof source[k] === 'object') {
target[k] = deepCopy(source[k])
} else {
target[k] = source[k]
}
}
}
return target
}
function isObject(obj) {
return typeof obj === 'object' && obj !== null
}
const newData = deepCopy(data)
</script>
手写深克隆
最新推荐文章于 2024-03-13 12:45:00 发布