数组/对象 深拷贝


很多同学在操作数组和对象的时候,如果只是简单地赋值,就和原来的数据同时发生改变
所以有了深拷贝的需要,话不多说,直接上代码:


export function deepClone ( obj) {
let result = Array. isArray( obj) ? [] : {}
for ( let key in obj) {
if ( obj[ key] !== null) {
if ( typeof ( obj[ key]) === 'object') {
result[ key] = deepClone( obj[ key])
} else {
result[ key] = obj[ key]
}
} else {
result[ key] = null
}
}
return result
}

猜你喜欢

转载自blog.csdn.net/mrfano/article/details/79913184