JavaScript判断各种数据类型

  • typeof ,只可判断部分数据的数据类型
    • 数字
    • 字符串
    • 布尔值
    • undefined
    • function
  • Object.prototype.toString.call() , 通用
function estimateDataType(data) {
  const type = Object.prototype.toString.call(data)
  return type.match(/^\[object (\w+)\]$/)[1]
}

estimateDataType(1)     // Number
estimateDataType('abc') // String
estimateDataType(true)  // Boolean
estimateDataType(undefined) // Undefined
estimateDataType(null)  // Null
estimateDataType({})   // Object
estimateDataType([])   // Array

猜你喜欢

转载自www.cnblogs.com/guojbing/p/10601333.html