# 深拷贝浅拷贝

  1. 考虑数组
  2. 考虑嵌套
  3. 考虑无限循环(Map vs WeakMap)
  4. 性能优化(for while)
  5. 其他类型(function、RegExp、Date等)
/**
 * 深拷贝
 * @param {Object} obj 要拷贝的对象
 * @returns 拷贝后的结果
 */
function deepClone(obj, map = new WeakMap()) {
    // obj 是 null ,或者不是对象和数组,直接返回(包括function)
    if (typeof obj !== 'object' || obj == null) return obj;

    // 防止循环引用
    if (map.has(obj)) {
        return map.get(obj);
    }

    // 判断是否为几种特殊需要处理的类型
    let type = [Date, RegExp, Set, Map, WeakMap, WeakSet];
    if(type.includes(obj.constructor)) {
        return new obj.constructor(obj);
    }

    // 拷贝
    let result = {};
    if (obj instanceof Array) { // 考虑数组
        result = [];
    }

    map.set(obj, result);

    for (let key in obj) {
        // 保证 key 不是原型的属性
        if (obj.hasOwnProperty(key)) {
            // 递归调用
            result[key] = deepClone(obj[key], map);
        }
    }

    // 返回结果
    return result;
}

const target = {
    field: 1,
    field2: undefined,
    field3: {
        child: 'child'
    },
    field4: [2,4,8],
    field5: new Date(),
    field6: function() {console.log('123')},
    field7: new RegExp('123'),
    field8: new Set([1,2,3,4]),
    field9: new Map([['name', '张三'],['title', 'Author']]),
};
// target.target = target;

let result = deepClone(target);
console.log(result);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57

# weakMap vs Map

  • WeakMap只能以对象作为键,Map可以是基础数据类型
  • WeakMap的键是弱引用的,可能会在某个时刻被GC回收

如何写出一个惊艳面试官的深拷贝 (opens new window)

上次更新: 1/5/2022, 9:25:14 AM