判断js中的数据类型有一下几种方法:typeof、instanceof、 constructor、 prototype、 $.type()/jquery.type(),接下来主要比较一下这几种方法的异同。
例子:
var a = "iamstring.";var b = 222;var c= [1,2,3];var d = new Date();var e = function(){alert(111);};var f = function(){this.name="22";};结果:
alert(typeof a) ------------> string
alert(typeof b) ------------> number
alert(typeof c) ------------> object
alert(typeof d) ------------> object
alert(typeof e) ------------> function
alert(typeof f) ------------> function
下表总结了
typeof可能的返回值| 类型 | 结果 |
|---|---|
| Undefined | "undefined" |
| Null | "object"(见下文) |
| Boolean | "boolean" |
| Number | "number" |
| String | "string" |
| Symbol (ECMAScript 6 新增) | "symbol" |
| 宿主对象(由JS环境提供) | Implementation-dependent |
| 函数对象([[Call]] 在ECMA-262条款中实现了) | "function" |
| 任何其他对象 | "object" |
由以上结果可知
typeof在数组,正则,日期,对象上的判断并不好,都是返回object,由此可以引出另一个判断方法Object.prototype.toString(),在判断以上类型的时候建议使用Object.prototype.toString.call()例子:
var toString = Object.prototype.toString;
toString.call(new Date);//[object Date]
toString.call(new String);//[object String]
toString.call(Math);//[object Math]
toString.call(undefined);//[object Undefined]
toString.call(null);//[object Null]
toString.call([1,2,3,4]);//[object Array]
可以通过toString()来获取每个对象的类型。为了每个对象都能通过Object.prototype.toString()来检测,需要以Function.prototype.call()或者Function.prototype.apply()的形式来调用,
传递要检查的对象作为第一个参数,称为thisArg。
var toString = Object.prototype.toString; toString.call(new Date); // [object Date] toString.call(new String); // [object String] toString.call(Math); // [object Math] //Since JavaScript 1.8.5 toString.call(undefined); // [object Undefined] toString.call(null); // [object Null]
在可以使用jq的情况下,可以使用jquery.type()来判断数据类型
例子:
jQuery.type( true ) === "boolean"jQuery.type( 3 ) === "number"jQuery.type( "test" ) === "string"jQuery.type( function(){} ) === "function"jQuery.type( [] ) === "array"jQuery.type( new Date() ) === "date"jQuery.type( new Error() ) === "error" // as of jQuery 1.9jQuery.type( /test/ ) === "regexp"简单来说,通常情况下用typeof 判断就可以了,遇到预知Object类型的情况可以选用instanceof或constructor方法,实在没辙就使用$.type()方法。
浙公网安备 33010602011771号