# 实现深拷贝函数

  // 工具函数
  const _toString = Object.prototype.toString;
  const map = {
    array: 'Array',
    object: 'Object',
    function: 'Function',
    string: 'String',
    null: 'Null',
    undefined: 'Undefined',
    boolean: 'Boolean',
    number: 'Number'
  }
  const getType = (item) => {
    return _toString.call(item).slice(8, -1)
  }
  const isTypeOf = (item, type) => {
    return map[type] && map[type] === getType(item)
  }
  // 拷贝方法
  function cloneObj(obj) {
    if(!isTypeOf(obj, 'array') && !isTypeOf(obj, 'object')) {
      return obj
    }
    let newObj = obj instanceof Array ? [] : {};
    Object.keys(obj).forEach(key => {
      newObj[key] = cloneObj(obj[key])
    })
    return newObj
  }
  // 示例
  let obj1 = { name: 'zhu', age: 10, info: { id: 0, shop: '宁波' }, arr: [1, 2, 3, 4]};
  let obj2 = cloneObj(obj1);
  obj1.name = 'ke';
  console.log(obj1);
  console.log(obj2);
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