数据类型判断

162 阅读1分钟

typeof

typeof 可以辨识 8种类型,

  • undefined
  • string
  • number
  • boolean
  • object
  • function
  • symbol
  • BigInt

其中不能识别 null

typeof null // 'object'

前面讲过

在 JavaScript 中 二进制前三位都为 0 的话会被判断为 object 类型,null 的二进制表示全0,自然前三位也是 0,所以执行 typeof 时会返回 “object”。

还有就是 Array,Date,RegExp,这些引用类型无法识别。

typeof [] // 'object'
typeof new Date() // 'object'
typeof /a/g // 'object'

instanceof

object instanceof constructor
  • object

    某个实例对象

  • constructor

    某个构造函数

instanceof 运算符用来检测 constructor.prototype 是否存在于参数 object 的原型链上。

这样也能识别出类型

[] instanceof Array // true

但是也有几个问题

  • 数组 prototype 的原型链上有 Object
[] instanceof Object // true
  • 实例的prototype可以改写
  • 基础类型 例如 String,没有prototype

所以 instanceof 可以否掉了

Object.prototype.toString.call()

es5.github.io/#x15.2.4.2

When the toString method is called, the following steps are taken:

  1. If the this value is undefined, return "[object Undefined]".
  2. If the this value is null, return "[object Null]".
  3. Let O be the result of calling ToObject passing the this value as the argument.
  4. Let class be the value of the [[Class]] internal property of O.
  5. Return the String value that is the result of concatenating the three Strings "[object ", class, and "]".

调用该方法时,将执行以下步骤:**toString**

  1. 如果未定义,则返回**"[object undefined]"。**
  2. 如果为空值,则返回**"[object Null]"。**
  3. O是调用ToObject传递值作为参数的结果。
  4. O的 [[类]] 内部属性的值。
  5. 返回 String 值,该值是连接三个字符串**"[对象**"、和**"]**"的结果。
Object.prototype.toString.call( [1,2,3] );
// "[object Array]"
Object.prototype.toString.call( /regex-literal/i );
// "[object RegExp]"

Object.prototype.toString.call() 在 你不知道的javascript 中卷中,有一些解释,感兴趣可以看看

isXXX, 比如 isArray

Array.isArray()