判斷js中的數據類型有一下幾種方法:typeof、instanceof、 constructor、 prototype、 $.type()/jquery.type(),接下來主要比較一下這幾種方法的異同。javascript
先舉幾個例子:java
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返回的類型都是字符串形式,需注意,例如: alert(typeof a == "string") -------------> true alert(typeof a == String) ---------------> false 另外typeof 能夠判斷function的類型;在判斷除Object類型的對象時比較方便。
alert(c instanceof Array) ---------------> true alert(d instanceof Date) alert(f instanceof Function) ------------> true alert(f instanceof function) ------------> false 注意:instanceof 後面必定要是對象類型,而且大小寫不能錯,該方法適合一些條件選擇或分支。
alert(c.constructor === Array) ----------> true alert(d.constructor === Date) -----------> true alert(e.constructor === Function) -------> true 注意: constructor 在類繼承時會出錯 eg: function A(){}; function B(){}; A.prototype = new B(); //A繼承自B var aObj = new A(); alert(aobj.constructor === B) -----------> true; alert(aobj.constructor === A) -----------> false; 而instanceof方法不會出現該問題,對象直接繼承和間接繼承的都會報true: alert(aobj instanceof B) ----------------> true; alert(aobj instanceof B) ----------------> true; 言歸正傳,解決construtor的問題一般是讓對象的constructor手動指向本身: aobj.constructor = A; //將本身的類賦值給對象的constructor屬性 alert(aobj.constructor === A) -----------> true; alert(aobj.constructor === B) -----------> false; //基類不會報true了;
alert(Object.prototype.toString.call(a) === ‘[object String]’) -------> true; alert(Object.prototype.toString.call(b) === ‘[object Number]’) -------> true; alert(Object.prototype.toString.call(c) === ‘[object Array]’) -------> true; alert(Object.prototype.toString.call(d) === ‘[object Date]’) -------> true; alert(Object.prototype.toString.call(e) === ‘[object Function]’) -------> true; alert(Object.prototype.toString.call(f) === ‘[object Function]’) -------> true; 大小寫不能寫錯,比較麻煩,但勝在通用。
若是對象是undefined或null,則返回相應的「undefined」或「null」。
jQuery.type( undefined ) === "undefined" jQuery.type() === "undefined" jQuery.type( window.notDefined ) === "undefined" jQuery.type( null ) === "null" 若是對象有一個內部的[[Class]]和一個瀏覽器的內置對象的 [[Class]] 相同,咱們返回相應的 [[Class]] 名字。 (有關此技術的更多細節。 ) 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.9 jQuery.type( /test/ ) === "regexp" 其餘一切都將返回它的類型「object」。
一般狀況下用typeof 判斷就能夠了,遇到預知Object類型的狀況能夠選用instanceof或constructor方法,實在沒轍就使用$.type()方法。jquery