Typeof

typeof 对于基本类型,除了 null 都可以显示正确的类型

  1. typeof 1 // 'number'
  2. typeof '1' // 'string'
  3. typeof undefined // 'undefined'
  4. typeof true // 'boolean'
  5. typeof Symbol() // 'symbol'
  6. typeof b // b 没有声明,但是还会显示 undefined

typeof 对于对象,除了函数都会显示 object

  1. typeof [] // 'object'
  2. typeof {} // 'object'
  3. typeof console.log // 'function'

对于 null 来说,虽然它是基本类型,但是会显示 object,这是一个存在很久了的 Bug

  1. typeof null // 'object'

PS:为什么会出现这种情况呢?因为在 JS 的最初版本中,使用的是 32 位系统,为了性能考虑使用低位存储了变量的类型信息,000 开头代表是对象,然而 null 表示为全零,所以将它错误的判断为 object 。虽然现在的内部类型判断代码已经改变了,但是对于这个 Bug 却是一直流传下来。

如果我们想获得一个变量的正确类型,可以通过 Object.prototype.toString.call(xx)。这样我们就可以获得类似 [object Type] 的字符串。

  1. let a
  2. // 我们也可以这样判断 undefined
  3. a === undefined
  4. // 但是 undefined 不是保留字,能够在低版本浏览器被赋值
  5. let undefined = 1
  6. // 这样判断就会出错
  7. // 所以可以用下面的方式来判断,并且代码量更少
  8. // 因为 void 后面随便跟上一个组成表达式
  9. // 返回就是 undefined
  10. a === void 0