更新日期: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
用于缓存已经访问过的对象,如果再次访问到这个对象,可以直接使用缓存的值,用于解决循环引用的问题和优化性能; -
copyArray
、copySet
、copyMap
、copyObject
中都调用了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);
}