js 比typeof 更准判断数据类型 更好用的判断语句

平时我们大多数人都用 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()   当然有更好的方式 欢迎来指教



猜你喜欢

转载自blog.csdn.net/u013809856/article/details/77043396
今日推荐