js深拷贝面试题

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>深拷贝</title>
</head>

<body>
  <script>
    const obj1 = {
      array: [1, 2],
      arrayOfObj: [{ a: 3 }, { b: 4 }],
      obj: { c: 5 },
      reg: /7/,
      data: new Date(),
      map: new Map([['d', 8], ['e', 9]]),
      set: new Set([10, 11]),
      num: 12,
      str: 'xxx',
      bol: false,
      fn: function () { console.log(13) },
      nulVal: null,
      undVal: undefined
    }

    function cloneDeep (obj = {}, cacheMap = new WeakMap()) {

      if (typeof obj !== "object" || !obj) {
        return obj
      }

      if (cacheMap.has(obj)) {
        return cacheMap.get(obj)
      }

      let temp, params;
      const constructor = obj.constructor;

      if (obj instanceof RegExp || obj instanceof Date) {
        params = obj
      }

      temp = new constructor(params)
      cacheMap.set(obj, temp)

      if (obj instanceof Map) {
        for (const [key, value] of obj) {
          temp.set(cloneDeep(key, cacheMap), cloneDeep(value, cacheMap))
        }
      } else if (obj instanceof Set) {
        for (const value of obj) {
          temp.add(cloneDeep(value, cacheMap))
        }
      } else {
        for (let key in obj) {
          if (obj.hasOwnProperty(key)) {
            temp[key] = cloneDeep(obj[key], cacheMap)
          }
        }
      }
      return temp;
    }

    const obj2 = {
      to: obj1
    }
    obj1.to = obj2

    const result = cloneDeep(obj1)
    console.log(obj1, result);
  </script>
</body>

</html>
posted @ 2023-02-12 15:39  iooz  阅读(28)  评论(0)    收藏  举报