1
const deepCopy = (instance) => {
  // 递归开始,判断参数是数组还是对象
  const result = Array.isArray(instance) ? [] : instance instanceof Object ? {} : null
  if (result === null) {
    throw new Error(`需要传入Array或Object类型的参数,但现在是${typeof instance}类型的参数`)
  }
  // 如果参数是数组,开启for循环遍历数组
  if (Array.isArray(instance)) {
    for (let i = 0; i < instance.length; i++) {
      const inst = instance[i]
      // 如果数组中某个索引对应的是对象,就对其进行递归并赋值,否则直接赋值
      result[i] = inst instanceof Object ? deepCopy(inst) : inst
    }
    // 如果参数是对象,开启for...in循环遍历对象
  } else if (instance instanceof Object) {
    for (const key in instance) {
      // 如果对象中某个key对应的是一个数组或者对象,那么就对其递归并赋值给当前值,否则直接赋值
      const condition = Array.isArray(instance[key]) || instance[key] instanceof Object
      result[key] = condition ? deepCopy(instance[key]) : instance[key]
    }
  }
  return result
}

_香蕉大神
98 声望1 粉丝

努力变强(tu)?!