Javascript数据类型判断

51 阅读1分钟

《用得上的前端知识》系列 - 你我都很忙,能用100字说清楚,绝不写万字长文

类型判断函数的实现

function getType(v) {
  // `null`
  if (v === null) return 'null'

  const baseType = typeof v
  // `undefined``number``string``boolean``symbol``bigInt``function`
  if (baseType !== 'object') return baseType

  // `arguments``error``date``regExp``object`
  // `map``set``weakmap``weakset`
  // 基本类型的包装类型按照其基本类型返回
  const builtinType = Object.prototype.toString.call(v)
    .slice(8, -1).toLocaleLowerCase()

  return builtinType
}

类型判断的方法

typeof

  • 可判断类型:Undefined、Number、String、Boolean、Symbol、BigInt、Function;
  • 容易出现的问题:typeof null === 'object'。

instanceof

  • instanceof 操作符左侧为引用类型,右侧为构造函数,作用是检测右侧构造函数的原型是否在左侧对象的原型链上出现过;

Object.prototype.toString

将各个类型传入Object.prototype.toString.call()的表现如下表:

传入变量类型返回结果
Undefined'[object Undefined]'
Null'[object Null]'
Boolean'[object Boolean]'
Number'[object Number]'
String'[object String]'
Symbol'[object Symbol]'
BigInt'[object BigInt]'
Object'[object Object]'
Array'[object Array]'
Function'[object Function]'
Arguments'[object Arguments]'
Set'[object Set]'
Map'[object Map]'
WeakSet'[object WeakSet]'
WeakMap'[object WeakMap]'
Date'[object Date]'
RegExp'[object RegExp]'
*Error'[object Error]'

注:*Error 代表所有错误类对象。

参考资料