判断JavaScript数据类型

169 阅读1分钟

typeof操作符可以准确判断一个变量是否为下面几个原始类型:

typeof 'ConardLi'  // string
typeof 123  // number
typeof true  // boolean
typeof Symbol()  // symbol
typeof undefined  // undefined

不适用场景

当你用typeof来判断引用类型时似乎显得有些乏力了:

instanceof操作符可以帮助我们判断引用类型具体是什么类型的对象:

[] instanceof Array // true
new Date() instanceof Date // true
new RegExp() instanceof RegExp // true

Object.prototype.toString.call()返回[object type]