DeepClone 原理
这里简单叙述一下,通过 DFS 深度优先遍历重新构建整个数据树(暂且这么叫吧~),分两种情况
- 基本数据类型,直接
key = value赋值就行 - 复杂数据类型,如
Date,RegExp等,通过new关键字重新创建实例
简单实现
逻辑很简单
- 若判断入参为
null或基本数据类型或Function,直接返回; - 若为数组,则创建新数组,遍历原数组的元素,使用
deepClone递归得到新元素; - 若为
Object,则区分复杂对象和简单对象即可,简单对象和数组流程一样。
function deepClone(data) {
if (data === null || typeof data !== 'object' || typeof data === 'function') {
return data;
}
if (Array.isArray(data)) {
const newArr = [];
data.forEach(el => {
newArr.push(deepClone(el));
});
return newArr;
}
if (typeof data === 'object') {
if (data instanceof Date) {
return new Date(data.getTime());
}
if (data instanceof RegExp) {
return new RegExp(data.source);
}
const keys = Object.keys(data);
const newObj = {};
keys.forEach(key => {
newObj[key] = deepClone(data[key]);
});
return newObj;
}
}