JS的typeof力所能及已经力所不及

typeof返回值列表

typeof的作用

返回参数的类型

typeof能判断的类型

  1. String类型: typeof 'a' === 'string'
  2. Undefined类型: typeof undefined === 'undefined'
  3. Boolean类型: typeof true === 'boolean'
  4. Number类型: typeof 22 === 'number'
  5. Symbol类型: typeof Symbol() === 'symbol'
  6. Function类型:typeof function(){} === 'function'

typeof不能判断的类型

  1. Null类型: typeof null === 'object'
  2. Array类型: typeof [] === 'object'
  3. 除去Array/Function类型的对象: typeof {} === 'object'

typeof不能判断的类型,该如何去判断?

  1. Null类型的值有且仅有一个值null 因此可以通过值比较进行判断:
const a = null
if (a === null) {
  console.log('a是Null类型')
} else {
  console.log('a不是Null类型')
}
  1. 判断是否是数组
Object.prototype.toString.call([]) === '[Object Array]'
  1. 判断是否是普通对象
Object.prototype.toString.call({}) === '[Object Object]'
posted @ 2018-03-12 11:39  Plortinus  阅读(186)  评论(0编辑  收藏  举报