【JS/TS】这也许是全网最接近完美的深拷贝函数

更新日期:2024/02/21
更新说明:考虑类更多的情况,能拷贝更多类型的对象了,也保留了原型链。

代码

老样子,先上完整代码(js版的深拷贝函数在文章最后):

/**
 * 深拷贝
 * @param source 原数据,可以是原始值、一般对象、数组、Map、Set、Date等
 */
function deepcopy<T>(source: T): T {
    const cache: WeakMap<any, any> = new WeakMap<any, any>();
    
    /**
     * 深拷贝数组
     * @param source
     */
    const copyArray = (source: any[]): any[] => {
        const result: any[] = [];
        cache.set(source, result);
        source.forEach((item) => {
            result.push(dfs(item));
        });
        return result;
    };
    
    /**
     * 深拷贝集合
     * @param source
     */
    const copySet = (source: Set<any>): Set<any> => {
        const result: Set<any> = new Set<any>();
        cache.set(source, result);
        source.forEach((item) => {
            result.add(dfs(item));
        });
        return result;
    };
    
    /**
     * 深拷贝映射
     * @param source
     */
    const copyMap = (source: Map<any, any>): Map<any, any> => {
        const result: Map<any, any> = new Map<any, any>();
        cache.set(source, result);
        source.forEach((value, key) => {
            result.set(key, dfs(value));
        });
        return result;
    };
    
    /**
     * 拷贝正则表达式
     * @param source
     */
    const copyRegExp = (source: RegExp): any => {
        const result: RegExp = new RegExp(source.source, source.flags);
        result.lastIndex = source.lastIndex;
        return result;
    }
    
    /**
     * 深拷贝对象
     * @param source
     */
    const copyObject = (source: any): object => {
        if (source === null) {
            return null;
        }
        
        const Ctor = source.constructor;
        switch (Ctor) {
            case Array: {
                return copyArray(source);
            }
            case Map: {
                return copyMap(source);
            }
            case Set: {
                return copySet(source);
            }
            case Date:
            case Number:
            case String: {
                return copyByCtor(Ctor, source);
            }
            case Boolean: {
                return copyByCtor(Ctor, source.valueOf());
            }
            case RegExp: {
                return copyRegExp(source);
            }
            default: {
                break;
            }
        }
        
        const result: object = Object.create(Reflect.getPrototypeOf(source));
        cache.set(source, result);
        
        // 拷贝所有属性描述符
        for (const key of Reflect.ownKeys(source)) {
            const descriptor = Reflect.getOwnPropertyDescriptor(source, key);
            const newDescriptor = { ...descriptor };
            if ("value" in descriptor) {
                newDescriptor.value = dfs(source[key]);
            }
            Reflect.defineProperty(result, key, newDescriptor);
        }
        
        return result;
    };
    
    /**
     * 拷贝Date
     * @param Ctor
     * @param source
     */
    const copyByCtor = <T>(Ctor: { new(source: T) }, source: T): T => {
        return new Ctor(source);
    };
    
    /**
     * 深度优先遍历
     * @param source
     */
    const dfs = (source: any): any => {
        if (typeof source !== "object") {
            return source;
        }
        
        if (cache.has(source)) {
            return cache.get(source);
        }
        
        return copyObject(source);
    };
    
    return dfs(source);
}

测试

使用 nodejs v20.9.0 / typescript v5.2.2 / ts-node v10.9.1 进行测试

(function testDeepCopy() {
    // region 测试基本数据类型
    console.log("测试基本数据类型");
    
    const num = 10;
    const str = "hello";
    const bool = true;
    const symbol = Symbol("symbol");
    const bigint = BigInt(10);
    const undefinedValue = void 0;
    
    console.log("num", deepcopy(num));
    console.log("str", deepcopy(str));
    console.log("bool", deepcopy(bool));
    console.log("symbol", deepcopy(symbol));
    console.log("bigint", deepcopy(bigint));
    console.log("undefinedValue", deepcopy(undefinedValue));
    // endregion
    
    // region 测试数组
    console.log(" \n测试数组");
    
    const arr1 = [1, 2, 3];
    const arr2 = [{ name: "Alice" }, { name: "Bob" }];
    
    console.log("arr1", deepcopy(arr1));
    console.log("arr2", deepcopy(arr2));
    // endregion
    
    // region 测试对象
    console.log(" \n测试对象");
    
    const objNull = null;
    const objByNull = Object.create(null);
    const obj1 = { name: "Alice", age: 20 };
    const obj2 = { nested: { prop: "value" } };
    
    console.log("objNull", deepcopy(objNull));
    console.log("objByNull", deepcopy(objByNull));
    console.log("obj1", deepcopy(obj1));
    console.log("obj2", deepcopy(obj2));
    // endregion
    
    // region 测试集合
    const set1 = new Set([1, 2, 3]);
    const set2 = new Set([{ name: "Alice" }, { name: "Bob" }]);
    
    console.log("set1", deepcopy(set1));
    console.log("set2", deepcopy(set2)); // Set(2) { { name: "Alice" }, { name: "Bob" } }
    // endregion
    
    // region 测试映射
    console.log(" \n测试映射");
    
    const map1 = new Map([[1, "one"], [2, "two"]]);
    const map2 = new Map([[{ name: "Alice" }, { age: 20 }], [{ name: "Bob" }, { age: 25 }]]);
    
    console.log("map1", deepcopy(map1));
    console.log("map2", deepcopy(map2));
    // endregion
    
    // region 测试Date
    console.log(" \n测试Date");
    
    const date = new Date(1708494897476);
    
    console.log("date", deepcopy(date));
    // endregion
    
    // region 测试正则表达式
    console.log(" \n测试正则表达式");
    
    const reg = /[a-z]*/g;
    
    console.log("reg", deepcopy(reg));
    // endregion
    
    // region 测试包装对象
    console.log(" \n测试包装对象");
    
    const numberObj = new Number(1);
    const stringObj = new String("1");
    const booleanObj = new Boolean(false);
    
    console.log("numberObj", deepcopy(numberObj));
    console.log("stringObj", deepcopy(stringObj));
    console.log("booleanObj", deepcopy(booleanObj));
    // endregion
    
    // region 测试循环引用
    console.log(" \n测试循环引用");
    
    const obj3 = { name: "Alice" };
    const obj4 = { name: "Bob" };
    const obj5 = { name: "John" };
    obj3["self"] = obj3;
    obj3["friends"] = [obj4, obj5];
    obj4["self"] = obj4;
    obj4["friends"] = [obj3, obj5];
    obj5["self"] = obj5;
    obj5["friends"] = [obj3, obj4];
    
    console.log("obj3", deepcopy(obj3));
    console.log("obj4", deepcopy(obj4));
    console.log("obj5", deepcopy(obj5));
    // endregion
})();

打印结果:

测试基本数据类型
num10
str hello
booltrue
symbolSymbol(symbol)
bigint10n
undefinedValueundefined

测试数组
arr1 [1,2,3 ]
arr2 [ { name:'Alice' }, { name:'Bob' } ]

测试对象
objNullnull
objByNull [Object: null prototype] {}
obj1 { name:'Alice', age:20 }
obj2 { nested: { prop:'value' } }
set1 Set(3) {1,2,3 }
set2 Set(2) { { name:'Alice' }, { name:'Bob' } }

测试映射
map1 Map(2) {1 =>'one',2 =>'two' }
map2 Map(2) {
  { name:'Alice' } => { age:20 },
  { name:'Bob' } => { age:25 },
}

测试Date
date 2024-02-21T05:54:57.476Z

测试正则表达式
reg /[a-z]*/g

测试包装对象
numberObj [Number: 1]
stringObj [String: '1']
booleanObj [Boolean: false]

测试循环引用
obj3 <ref *1> {
  name: 'Alice',
  self: [Circular *1],
  friends: [
    <ref *2> {
      name: 'Bob',
      self: [Circular *2],
      friends: [Array]
    },
    <ref *3> {
      name: 'John',
      self: [Circular *3],
      friends: [Array]
    }
  ]
}
obj4 <ref *1> {
  name: 'Bob',
  self: [Circular *1],
  friends: [
    <ref *2> {
      name: 'Alice',
      self: [Circular *2],
      friends: [Array]
    },
    <ref *3> {
      name: 'John',
      self: [Circular *3],
      friends: [Array]
    }
  ]
}
obj5 <ref *1> {
  name: 'John',
  self: [Circular *1],
  friends: [
    <ref *2> {
      name: 'Alice',
      self: [Circular *2],
      friends: [Array]
    },
    <ref *3> {
      name: 'Bob',
      self: [Circular *3],
      friends: [Array]
    }
  ]
}

原理讲解

  • WeakMap用于缓存已经访问过的对象,如果再次访问到这个对象,可以直接使用缓存的值,用于解决循环引用的问题和优化性能;
  • copyArraycopySetcopyMapcopyObject中都调用了dfs函数,而dfs又会调用他们,直到遇到null、基本数据类型或者已经缓存过的对象时返回。如果对象中没有循环引用,那么它就是一棵;如果存在了循环引用,它就变成了。我们可以发现,这实际上就是图(树也可以看成没有环的图)的深度优先遍历(同义词:深度优先搜索)
  • 某些js内置类的实例无法使用遍历对象属性的方式复制,只能使用它们的构造函数创建,比如包装类、Date、Map、Set等;
  • 通过对象的构造函数来判断当前对象是什么类型,再使用不同的方式复制;
  • 函数的返回类型和原对象的类型一致;

说明

平常开发中如果需要完整复制一个对象,最常用的方法是使用Json的序列化和反序列化,也就是JSON.parse(JSON.stringify(obj))
虽然这个方法很简单,但是它却有很多致命问题,比如:

  • 无法复制函数、symbol等,值为undefined的属性也会丢失;
  • 无法处理循环引用;
  • 无法复制特殊对象,比如Set、Map等;

而本文给出的深拷贝函数有以下优点

  • 可以复制原始值、函数、Set、Map、数组、一般对象等;
  • 可以复制对象中以Symbol类型为键的值;
  • 保留了原型链;
  • 保留了属性描述符,
  • 解决循环引用问题;
  • 拷贝返回的变量类型和传入时的变量类型一致;

当然本文的函数也有一些缺点

  • 由于处理了循环引用的问题,效率会降低,内存占用会升高;
  • 对于js内置构造方法只支持了一部分常用的,ArrayBuffer、TypedArray(Uint8Array、Uint16Array等)、DataView等并没有支持,可以自行处理;
  • 如果对象的构造方法继承了某些内置构造方法,比如Set、Map等,将无法正常拷贝,需要自行处理;
  • 如果在Set、Map、Date等对象上增加了自定义属性,这些属性并不会被复制。
  • 如果对象的递归层数很多,可能造成递归栈溢出,可以使用数组来模拟堆栈;

另外,由于用到了Map、Set、反射(Reflect)等功能,ES的版本要求至少为ES6(ES2015),Reflect相关方法可以使用Object的相关方法代替。

Javascript版

/**
 * 深拷贝
 * @template T
 * @param source {T} 原数据,可以是原始值、一般对象、数组、Map、Set、Date等
 * @return {T}
 */
function deepcopy(source) {
    const cache = new WeakMap();
    
    /**
     * 深拷贝数组
     * @param source
     */
    const copyArray = (source) => {
        const result = [];
        cache.set(source, result);
        source.forEach((item) => {
            result.push(dfs(item));
        });
        return result;
    };
    
    /**
     * 深拷贝集合
     * @param source
     */
    const copySet = (source) => {
        const result = new Set();
        cache.set(source, result);
        source.forEach((item) => {
            result.add(dfs(item));
        });
        return result;
    };
    
    /**
     * 深拷贝映射
     * @param source
     */
    const copyMap = (source) => {
        const result = new Map();
        cache.set(source, result);
        source.forEach((value, key) => {
            result.set(key, dfs(value));
        });
        return result;
    };
    
    /**
     * 拷贝正则表达式
     * @param source
     */
    const copyRegExp = (source) => {
        const result = new RegExp(source.source, source.flags);
        result.lastIndex = source.lastIndex;
        return result;
    };
    
    /**
     * 深拷贝对象
     * @param source
     */
    const copyObject = (source) => {
        if (source === null) {
            return null;
        }
        
        const Ctor = source.constructor;
        switch (Ctor) {
            case Array: {
                return copyArray(source);
            }
            case Map: {
                return copyMap(source);
            }
            case Set: {
                return copySet(source);
            }
            case Date:
            case Number:
            case String: {
                return copyByCtor(Ctor, source);
            }
            case Boolean: {
                return copyByCtor(Ctor, source.valueOf());
            }
            case RegExp: {
                return copyRegExp(source);
            }
            default: {
                break;
            }
        }
        
        const result = Object.create(Reflect.getPrototypeOf(source));
        cache.set(source, result);
        
        // 拷贝所有属性描述符
        for (const key of Reflect.ownKeys(source)) {
            const descriptor = Reflect.getOwnPropertyDescriptor(source, key);
            const newDescriptor = { ...descriptor };
            if ("value" in descriptor) {
                newDescriptor.value = dfs(source[key]);
            }
            Reflect.defineProperty(result, key, newDescriptor);
        }
        
        return result;
    };
    
    /**
     * 拷贝Date
     * @param Ctor
     * @param source
     */
    const copyByCtor = (Ctor, source) => {
        return new Ctor(source);
    };
    
    /**
     * 深度优先遍历
     * @param source
     */
    const dfs = (source) => {
        if (typeof source !== "object") {
            return source;
        }
        
        if (cache.has(source)) {
            return cache.get(source);
        }
        
        return copyObject(source);
    };
    
    return dfs(source);
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 216,402评论 6 499
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,377评论 3 392
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 162,483评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,165评论 1 292
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,176评论 6 388
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,146评论 1 297
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,032评论 3 417
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,896评论 0 274
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,311评论 1 310
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,536评论 2 332
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,696评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,413评论 5 343
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,008评论 3 325
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,659评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,815评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,698评论 2 368
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,592评论 2 353

推荐阅读更多精彩内容