• 你最少用几行代码实现深拷贝?


    问题分析

    深拷贝 自然是 相对 浅拷贝 而言的。 我们都知道 引用数据类型 变量存储的是数据的引用,就是一个指向内存空间的指针, 所以如果我们像赋值简单数据类型那样的方式赋值的话,其实只能复制一个指针引用,并没有实现真正的数据克隆。

    通过这个例子很容易就能理解:

    1. const obj1 = {
    2. name: 'superman'
    3. }
    4. const obj2 = obj1;
    5. obj1.name = '前端切图仔';
    6. console.log(obj2.name); // 前端切图仔
    7. 复制代码

    所以深度克隆就是为了解决引用数据类型不能被通过赋值的方式 复制 的问题。

    引用数据类型

    我们不妨来罗列一下引用数据类型都有哪些:

    • ES6之前: Object, Array, Date, RegExp, Error,
    • ES6之后: Map, Set, WeakMap, WeakSet,

    所以,我们要深度克隆,就需要对数据进行遍历并根据类型采取相应的克隆方式。 当然因为数据会存在多层嵌套的情况,采用递归是不错的选择。

    简单粗暴版本

    1. function deepClone(obj) {
    2. let res = {};
    3. // 类型判断的通用方法
    4. function getType(obj) {
    5. return Object.prototype.toString.call(obj).replaceAll(new RegExp(/\[|\]|object /g), "");
    6. }
    7. const type = getType(obj);
    8. const reference = ["Set", "WeakSet", "Map", "WeakMap", "RegExp", "Date", "Error"];
    9. if (type === "Object") {
    10. for (const key in obj) {
    11. if (Object.hasOwnProperty.call(obj, key)) {
    12. res[key] = deepClone(obj[key]);
    13. }
    14. }
    15. } else if (type === "Array") {
    16. console.log('array obj', obj);
    17. obj.forEach((e, i) => {
    18. res[i] = deepClone(e);
    19. });
    20. }
    21. else if (type === "Date") {
    22. res = new Date(obj);
    23. } else if (type === "RegExp") {
    24. res = new RegExp(obj);
    25. } else if (type === "Map") {
    26. res = new Map(obj);
    27. } else if (type === "Set") {
    28. res = new Set(obj);
    29. } else if (type === "WeakMap") {
    30. res = new WeakMap(obj);
    31. } else if (type === "WeakSet") {
    32. res = new WeakSet(obj);
    33. }else if (type === "Error") {
    34. res = new Error(obj);
    35. }
    36. else {
    37. res = obj;
    38. }
    39. return res;
    40. }
    41. 复制代码

    其实这就是我们最前面提到的第二种方式,很傻对不对,明眼人一眼就能看出来有很多冗余代码可以合并。

    我们先进行最基本的优化:

    合并冗余代码

    将一眼就能看出来冗余的代码合并下。

    1. function deepClone(obj) {
    2. let res = null;
    3. // 类型判断的通用方法
    4. function getType(obj) {
    5. return Object.prototype.toString.call(obj).replaceAll(new RegExp(/\[|\]|object /g), "");
    6. }
    7. const type = getType(obj);
    8. const reference = ["Set", "WeakSet", "Map", "WeakMap", "RegExp", "Date", "Error"];
    9. if (type === "Object") {
    10. res = {};
    11. for (const key in obj) {
    12. if (Object.hasOwnProperty.call(obj, key)) {
    13. res[key] = deepClone(obj[key]);
    14. }
    15. }
    16. } else if (type === "Array") {
    17. console.log('array obj', obj);
    18. res = [];
    19. obj.forEach((e, i) => {
    20. res[i] = deepClone(e);
    21. });
    22. }
    23. // 优化此部分冗余判断
    24. // else if (type === "Date") {
    25. // res = new Date(obj);
    26. // } else if (type === "RegExp") {
    27. // res = new RegExp(obj);
    28. // } else if (type === "Map") {
    29. // res = new Map(obj);
    30. // } else if (type === "Set") {
    31. // res = new Set(obj);
    32. // } else if (type === "WeakMap") {
    33. // res = new WeakMap(obj);
    34. // } else if (type === "WeakSet") {
    35. // res = new WeakSet(obj);
    36. // }else if (type === "Error") {
    37. // res = new Error(obj);
    38. //}
    39. else if (reference.includes(type)) {
    40. res = new obj.constructor(obj);
    41. } else {
    42. res = obj;
    43. }
    44. return res;
    45. }
    46. 复制代码

    为了验证代码的正确性,我们用下面这个数据验证下:

    1. const map = new Map();
    2. map.set("key", "value");
    3. map.set("ConardLi", "coder");
    4. const set = new Set();
    5. set.add("ConardLi");
    6. set.add("coder");
    7. const target = {
    8. field1: 1,
    9. field2: undefined,
    10. field3: {
    11. child: "child",
    12. },
    13. field4: [2, 4, 8],
    14. empty: null,
    15. map,
    16. set,
    17. bool: new Boolean(true),
    18. num: 2,
    19. str: '2',
    20. symbol: Object(Symbol(1)),
    21. date: new Date(),
    22. reg: /\d+/,
    23. error: new Error(),
    24. func1: () => {
    25. let t = 0;
    26. console.log("coder", t++);
    27. },
    28. func2: function (a, b) {
    29. return a + b;
    30. },
    31. };
    32. //测试代码
    33. const test1 = deepClone(target);
    34. target.field4.push(9);
    35. console.log('test1: ', test1);
    36. 复制代码

    执行结果:

     

    还有进一步优化的空间吗?

    答案当然是肯定的。

    1. // 判断类型的方法移到外部,避免递归过程中多次执行
    2. const judgeType = origin => {
    3. return Object.prototype.toString.call(origin).replaceAll(new RegExp(/\[|\]|object /g), "");
    4. };
    5. const reference = ["Set", "WeakSet", "Map", "WeakMap", "RegExp", "Date", "Error"];
    6. function deepClone(obj) {
    7. // 定义新的对象,最后返回
    8. //通过 obj 的原型创建对象
    9. const cloneObj = Object.create(Object.getPrototypeOf(obj), Object.getOwnPropertyDescriptors(obj));
    10. // 遍历对象,克隆属性
    11. for (let key of Reflect.ownKeys(obj)) {
    12. const val = obj[key];
    13. const type = judgeType(val);
    14. if (reference.includes(type)) {
    15. newObj[key] = new val.constructor(val);
    16. } else if (typeof val === "object" && val !== null) {
    17. // 递归克隆
    18. newObj[key] = deepClone(val);
    19. } else {
    20. // 基本数据类型和function
    21. newObj[key] = val;
    22. }
    23. }
    24. return newObj;
    25. }
    26. 复制代码

    执行结果如下:

     

    • Object.getOwnPropertyDescriptors()  方法用来获取一个对象的所有自身属性的描述符。
    • 返回所指定对象的所有自身属性的描述符,如果没有任何自身属性,则返回空对象。

    具体解释和内容见MDN 

    这样做的好处就是能够提前定义好最后返回的数据类型。

    这个实现参考了网上一位大佬的实现方式,个人觉得理解成本有点高,而且对数组类型的处理也不是特别优雅, 返回类数组。

    我在我上面代码的基础上进行了改造,改造后的代码如下:

    1. function deepClone(obj) {
    2. let res = null;
    3. const reference = [Date, RegExp, Set, WeakSet, Map, WeakMap, Error];
    4. if (reference.includes(obj?.constructor)) {
    5. res = new obj.constructor(obj);
    6. } else if (Array.isArray(obj)) {
    7. res = [];
    8. obj.forEach((e, i) => {
    9. res[i] = deepClone(e);
    10. });
    11. } else if (typeof obj === "object" && obj !== null) {
    12. res = {};
    13. for (const key in obj) {
    14. if (Object.hasOwnProperty.call(obj, key)) {
    15. res[key] = deepClone(obj[key]);
    16. }
    17. }
    18. } else {
    19. res = obj;
    20. }
    21. return res;
    22. }
    23. 复制代码

    虽然代码量上没有什么优势,但是整体的理解成本和你清晰度上我觉得会更好一点。那么你觉得呢?

    最后,还有循环引用问题,避免出现无线循环的问题。

    我们用hash来存储已经加载过的对象,如果已经存在的对象,就直接返回。

    1. function deepClone(obj, hash = new WeakMap()) {
    2. if (hash.has(obj)) {
    3. return obj;
    4. }
    5. let res = null;
    6. const reference = [Date, RegExp, Set, WeakSet, Map, WeakMap, Error];
    7. if (reference.includes(obj?.constructor)) {
    8. res = new obj.constructor(obj);
    9. } else if (Array.isArray(obj)) {
    10. res = [];
    11. obj.forEach((e, i) => {
    12. res[i] = deepClone(e);
    13. });
    14. } else if (typeof obj === "object" && obj !== null) {
    15. hash.set(obj);
    16. res = {};
    17. for (const key in obj) {
    18. if (Object.hasOwnProperty.call(obj, key)) {
    19. res[key] = deepClone(obj[key], hash);
    20. }
    21. }
    22. } else {
    23. res = obj;
    24. }
    25. return res;
    26. }
    27. 复制代码

    错误更正

    上文中对 Set Map weakMap weakSet 的处理存在问题,当key和value是对象时候,依然是浅克隆,为了避免误导JYM,这里暂且加个说明,大家可以帮忙想想如何解决。感谢 @要辣不要麻 大佬在评论区指出该问题。

    总结

    对于深拷贝的实现,可能存在很多不同的实现方式,关键在于理解其原理,并能够记住一种最容易理解和实现的方式,面对类似的问题才能做到 临危不乱,泰然自若。 上面的实现你觉得哪个更好呢?欢迎大佬们在评论区交流~

  • 相关阅读:
    Gvim显示行号、最大化、字号、主题等常用配置修改
    Luancher和unityLibrary都有build.gradle有什么不同
    IOS 设置UIViewController为背景半透明浮层弹窗,查看富文本图片详情
    Python中的3D矩阵操作
    【Python基础知识点总结】
    vue3项目中如何快速安装、配置并使用jQuery
    c++中httplib使用
    CentOS7和CentOS8 Asterisk 20.0.0 简单图形化界面4--使用libss7配置7号中继
    项目管理(影响项目的项目环境和管理过程)
    【Python教学】pyqt6入门到入土系列,超详细教学讲解
  • 原文地址:https://blog.csdn.net/m0_74931226/article/details/128017910