blog
blog copied to clipboard
30行代码实现深拷贝
const typeList = [
'string',
'number',
'undefined',
'boolean',
'function'
];
function isTypeList(obj) {
if (obj === null) {
return true;
}
const type = typeof obj;
return typeList.includes(type);
}
function deepCopy(value) {
if (isTypeList(value)) {
return value;
}
if (Array.isArray(value)) {
return value.map(item => deepCopy(item));
}
if (value instanceof Date) {
return new Date(value);
}
return Object.entries(value).reduce((preData, [key, val]) => {
preData[key] = deepCopy(val);
return preData;
}, {});
}