数据类型判断

55 阅读1分钟

主要的4个方法

  1. Object.prototype.toString.call()
  2. typeof
  3. instanceof
  4. constructor

其他特定类型方法

  • Array.isArray()
  • Number.isNaN() 比 isNaN() 更准确

Object.prototype.toString.call()

  • 最准确,可以判断所有情况
  • 返回 [object type]格式的字符串
Object.prototype.toString.call(1) // [object Number]

typeof 运算符

  • 只能处理基本类型除null 返回的是 Object)
  • 返回类型的字符串
  • 缺点:不能区分引用类型(Object/Array/Date/RegExp)
typeof 30 // 'number'
typeof Symbol() // 'symbol'
typeof BigInt(1) // 'bigInt'

instanceof 运算符

  • 主要检查构造函数的prototype是否在对象的原型链
  • 返回布尔值
  • 缺点:
    1. 不能检测基本类型;
    2. 原型链可能被修改,导致不可靠;
    3. 跨全局环境(iframe),不可靠;
[] instanceof Array // true
new Date instanceof Date // true
new RegExp instanceof RegExp // true

constructor 构造函数

  • 构造函数可随意修改,不可靠 不推荐使用

Array.isArray

  • 能准确检测是否是数组,更简洁
  • 返回布尔值
Array.isArray([]) // true