JavaScript 深拷贝
在进行赋值之前,为指针类型的数据成员另辟了一个独立的内存空间,实现真正内容上的拷贝。这种拷贝称为深拷贝。 ———— 百度百科
源码
⚠ 还有部分类型不支持
typescript:
/**
* 深克隆
* @param obj
*/
export function cloneDeep<T>(obj: T) {
if (obj instanceof Int8Array) return Int8Array.from(obj) as T;
if (obj instanceof Uint8Array) return Uint8Array.from(obj) as T;
if (obj instanceof Uint8ClampedArray) return Uint8ClampedArray.from(obj) as T;
if (obj instanceof Int16Array) return Int16Array.from(obj) as T;
if (obj instanceof Uint16Array) return Uint16Array.from(obj) as T;
if (obj instanceof Int32Array) return Int32Array.from(obj) as T;
if (obj instanceof Uint32Array) return Uint32Array.from(obj) as T;
if (obj instanceof Float32Array) return Float32Array.from(obj) as T;
if (obj instanceof Float64Array) return Float64Array.from(obj) as T;
if (obj instanceof ArrayBuffer) return new Int8Array(obj).buffer as T;
if (obj instanceof Set) return new Set(obj.values()) as T;
if (obj instanceof RegExp) return new RegExp(obj) as T;
if (obj instanceof Date) return new Date(+obj) as T;
if (typeof obj === "object") {
let res = (Array.isArray(obj) ? [] : {}) as T;
for (const key in obj) {
res[key] = cloneDeep(obj[key]);
}
return res;
}
return obj;
}
javascript:
/**
* 深克隆
* @param obj
*/
export function cloneDeep(obj) {
if (obj instanceof Int8Array) return Int8Array.from(obj);
if (obj instanceof Uint8Array) return Uint8Array.from(obj);
if (obj instanceof Uint8ClampedArray) return Uint8ClampedArray.from(obj);
if (obj instanceof Int16Array) return Int16Array.from(obj);
if (obj instanceof Uint16Array) return Uint16Array.from(obj);
if (obj instanceof Int32Array) return Int32Array.from(obj);
if (obj instanceof Uint32Array) return Uint32Array.from(obj);
if (obj instanceof Float32Array) return Float32Array.from(obj);
if (obj instanceof Float64Array) return Float64Array.from(obj);
if (obj instanceof ArrayBuffer) return new Int8Array(obj).buffer;
if (obj instanceof Set) return new Set(obj.values());
if (obj instanceof RegExp) return new RegExp(obj);
if (obj instanceof Date) return new Date(+obj);
if (typeof obj === "object") {
let res = Array.isArray(obj) ? [] : {};
for (const key in obj) {
res[key] = cloneDeep(obj[key]);
}
return res;
}
return obj;
}