第一种:typeof
typeof(function(){}) //"function"
typeof({}) //"object"
typeof(new Date()) //"object"
typeof(Date()) //"string"
typeof(RegExp('123')) //"object"
typeof([]) //"object"
typeof("123") //"string"
typeof(123) //"number"
typeof(null) //"object"
typeof(undefined) // "undefined"
typeof(true) //"boolean"
typeof(Symbol) //"function"
可以看到引用类型的数据([]和{})均返回object。同时,typeof也无法辨别像Date,RegExp等特殊的数据类型。Symbol类型和函数均返回function,然后看一看第二种方案:toString.call()
toString.call(Symbol) //"[object Function]"
toString.call(function(){}) //"[object Function]"
toString.call(true) //"[object Boolean]"
toString.call(new Date()) //"[object Date]"
toString.call(Date()) //"[object String]"
toString.call(RegExp('123')) //"[object RegExp]"
toString.call(null) //"[object Null]"
toString.call(undefined) //"[object Undefined]"
toString.call("123") //"[object String]"
toString.call(123) //"[object Number]"
toString.call([]) //"[object Array]"
toString.call({}) //"[object Object]"
[]和{}使用toString.call()得到了区分,但是Symbol类型和函数的返回仍然一致。最后看一下第三种方案:constructor
var fun = function(){}; fun.constructor === Function //true
var sym = Symbol(); sym.constructor === Symbol //true
值得注意的是,Date数据类型只有在new的时候才会是Date数据类型,否则是字符串类型
var date = new Date(); date.constructor === Date //true
var date = Date(); date.constructor === String //true