JS实现数据拷贝

95 阅读1分钟
   /**
   * 拷贝数据
   */
  function copyData (target) {
    // 先判断类型,再拷贝
    function checkType (val) {
      return Object.prototype.toString.call(val).slice(8, -1)
    }
    let res; const type = checkType(target)
    if (type === 'Object') {
      res = {}
    } else if (type === 'Array') {
      res = []
    } else {
      return target
    }
    // 数组和对象 for in 循环
    for (const i in target) { 
      const value = target[i]
      if (checkType(value) === 'Object' || checkType(value) === 'Array') { // 嵌套
        res[i] = copyData(value)
      } else { // 基本数据或者函数
        res[i] = value
      }
    }
    return res
  }

// 深拷贝对象
  function deepClone (obj) {
    const _toString = Object.prototype.toString
    // null, undefined, non-object, function
    if (!obj || typeof obj !== 'object') {
      return obj
    }
    // DOM Node
    if (obj.nodeType && 'cloneNode' in obj) {
      return obj.cloneNode(true)
    }
    // Date
    if (_toString.call(obj) === '[object Date]') {
      return new Date(obj.getTime())
    }
    // RegExp
    if (_toString.call(obj) === '[object RegExp]') {
      const flags = []
      if (obj.global) { flags.push('g') }
      if (obj.multiline) { flags.push('m') }
      if (obj.ignoreCase) { flags.push('i') }
      return new RegExp(obj.source, flags.join(''))
    }
    const result = Array.isArray(obj) ? [] : obj.constructor ? new obj.constructor() : {}
    for (const key in obj) {
      result[key] = deepClone(obj[key])
    }
    return result
  }