深拷贝

<!DOCTYPE html>
<html lang="zh-CN">
  <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 type="text/javascript">
      function deepClone(obj = {}) {
        // obj 是 null ,或者不是 object ,直接返回
        if (typeof obj !== 'object' || obj == null) {
          return obj
        }

        let result
        if (obj instanceof Array) {
          result = []
        } else {
          result = {}
        }

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

        return result
      }

      const obj1 = {
        name: '姓名1',
        age: 36,
        address: {
          city: 'beijing'
        },
        arr: [1, 2, 3]
      }

      const obj2 = deepClone(obj1)
      obj2.name = '姓名2'
      obj2.age = 40
      obj2.address.city = '广州'
      obj2.arr = [3, 4, 5]
      console.log(obj1)
      console.log(obj2)
    </script>
  </body>
</html>

posted @ 2021-03-01 15:41  CLM1010  阅读(46)  评论(0编辑  收藏  举报