js判断数据类型

54 阅读1分钟

js判断数据类型

(function () {
  let classType = {}
  let toString = classType.toString
  // 设定数据映射表
  let typeArray = ['String', 'Number', 'Boolean', 'Symbol', 'Object', 'Array', 'Function', 'RegExp', 'Date', 'Error']
  typeArray.forEach(item => {
    classType[`[object ${item}]`] = item.toLowerCase()
  })
  function toType(value) {
    // 值为null\undefined
    if (value == null) {
      return value + ''
    }
    // 值为其他
    return typeof value === 'object' || typeof value === 'function' ? classType[toString.call(value)] || 'object' :
      typeof value
  }
  window.toType = toType
})()