# 题目描述

实现浅拷贝和深拷贝

# 代码实现

# 1️⃣ 浅拷贝

// 使用Object.assign
const _shallowClone = target => {
    let newObj = Object.assign({}, target);
    return newObj;
}

// 使用target.hasOwnProperty(prop)
const _shallowClone = target => {
  if(typeof target === 'object' && target !== null) {
      const constructor = target.constructor
  if(/^(Function|RegExp|Date|Map|Set)$/i.test(constructor.name)) return target
      const cloneTarget = Array.isArray(target) ? [] : {}
      for(prop in target) {
          if(target.hasOwnProperty(prop)) {
              cloneTarget[prop] = target[prop]
          }
      }
      return cloneTarget
  } else {
      return target
  }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22

# 2️⃣ 简易版深拷贝

function test() {
  const o1 = { name: "g", age: 18, o: { name: "o" }, a: [1, 2] };
  const o2 = _sampleDeepClone(o1);
  const judge =
    JSON.stringify(o1) === JSON.stringify(o2) && o1.o !== o2.o && o1.a !== o2.a;
  return judge;
}


const _sampleDeepClone = target => {
  // 补全代码

  /*
      如果对象参数的数据类型不为“object”或为“null”,则直接返回该参数
      根据该参数的数据类型是否为数组创建新对象
      遍历该对象参数,将每一项递归调用该函数本身的返回值赋给新对象
  */

  if(typeof target !== "object" || target == null){
      return target;
  }
  // 参数是不是数组
  const cloneTarget = Array.isArray(target) ? [] : {};
  for(let prop in target){
      // 如果是对象类型,就递归
      if(target.hasOwnProperty(prop)){
         cloneTarget[prop] = typeof target[prop] == "object" ? _sampleDeepClone(target[prop]) : target[prop];            
      }
  }
  return cloneTarget;
}

console.log(test());
// true
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