Skip to content

devDeepClone 深拷贝

使用示例

ts
import {devDeepClone} from "devecoui-plus";

const value = ['a', 'b', 'c', 'd', 'e'];
const cloneValue = devDeepClone(value);
console.log(cloneValue); // ['a', 'b', 'c', 'd', 'e']

方法源码

ts
/**
 * 深拷贝对象(支持循环引用和特殊数据类型)
 * @param obj 需要拷贝的对象
 * @param map WeakMap 用于记录已拷贝对象,防止循环引用
 * @returns 深拷贝后的对象
 */
export function devDeepClone<T>(obj: T, map = new WeakMap()): T {
    if (obj === null || typeof obj !== 'object') return obj;

    if (map.has(obj)) return map.get(obj) as T;

    if (obj instanceof Date) return new Date(obj) as T;
    if (obj instanceof RegExp) return new RegExp(obj) as T;
    if (obj instanceof Set) return new Set([...obj].map(v => devDeepClone(v, map))) as T;
    if (obj instanceof Map) {
        return new Map([...obj.entries()].map(([k, v]) => [devDeepClone(k, map), devDeepClone(v, map)])) as T;
    }

    let result: any;
    if (Array.isArray(obj)) {
        result = [];
    } else {
        result = {} as T;
    }

    map.set(obj, result);

    for (const key in obj) {
        if (Object.prototype.hasOwnProperty.call(obj, key)) {
            result[key] = devDeepClone((obj as any)[key], map);
        }
    }

    return result;
}