数据类型检测

56 阅读1分钟

typeof

  • 优点:可以准确的判断 null 以外的原始数据类型与函数类型(undefined、boolean、number、string、symbol、bigInt、function
  • 缺点:数组、对象、null 都会被判断为 object

instanceof

  • 优点:可以准确的判断引用数据类型(object、array、function
  • 缺点:无法判断原始数据类型(boolean、number、string、symbol、bigInt),其中 nullundefined 不能使用 instanceof 运算符
  • 原理:instanceof 是一个运算符,用于检测构造函数的 prototype 属性是否存在于某个对象的原型链上

constructor

  • 优点:可以准确的判断 nullundefined 以外的数据类型(boolean、number、string、symbol、bigInt、object、array、function
  • 缺点:如果修改了目标对象的原型对象,检测结果会出现偏差

Object.prototype.toString.call()

  • 优点:可以准确的判断所有的数据类型
  • 原理:使用 Object 对象的原型方法 toString 来判断数据类型