深浅拷贝

深拷贝:克隆一个对象,数据相同,但引用地址不同

1
2
3
4
5
6
7
8
9
10
11
12
13
14
function deepClone(obj: any): any {
if (obj === null) return obj;
if (obj instanceof Date) return new Date(obj);
if (obj instanceof RegExp) return new RegExp(obj);
if (typeof obj !== 'object') return obj;
let res = Array.isArray(obj) ? [...obj] : { ...obj };
Object.keys(res).forEach((key) => {
res[key] = isObject(res[key]) ? deepClone(res[key]) : res[key];
});
return res;
};
function isObject(obj: any) {
return typeof obj === 'object' && typeof obj !== null;
}

浅拷贝:简单的说就是拷贝里面的基本类型数据,不拷贝里面的子对象

1
2
3
4
5
6
7
function shallowClone(obj) {
var c = {};
for (var key in obj) {
c[key] = obj[key]
}
return c;
}