平时我们大多数人都用 typeOf 操作符来检测数据类型 如:
typeof "John" // string
typeof 123 // number
typeof false // boolean
但 typeof [2] // object
typeof {name:"xu"} // object
typeof [2] 和 typeof {name:"xu"} 数组和对象 typeof 给出来都是 object
下面我跟大家说一种方法可以很方便检测数据类型(在JQ的$.type()源码中)
例子
var a = [];
var s = "str";
var o = {};
var day = new Date();
var fn = function(){};
{}.toString.call(a) == "[object Array]" // true
{}.toString.call(o) == "[object Object]" // true
{}.toString.call(s) == "[object String]" // true
{}.toString.call(day) == "[object Date]" //true
{}.toString.call(fn) == "[object Function]" //true
这是我看了JQ $.type的源码 {}.toString.call() 当然有更好的方式 欢迎来指教