在对数组或对象数据进行复制时,在编辑复制的数据时,使用深拷贝方法原有的数据不会受到影响。
以下代码可用于数组或对象的数据类型
const theObj = {
group: 'PUJI',
member: [
{name: 'Andy', year: '2010'},
{name: 'Andy', year: '2010'}
]
}
deepCopy = ( obj ) => {
if ( obj === null || typeof obj !== 'object' ) {
return obj;
}
if ( Array.isArray( obj ) ) {
return obj.map( ( item ) => deepCopy( item ) );
}
const newObj = {};
for ( const key in obj ) {
if ( obj.hasOwnProperty( key ) ) {
newObj[ key ] = deepCopy( obj[ key ] );
}
}
return newObj;
};
const result = deepCopy(theObj);
console.log( result );