對於類型的判斷,JavaScript用typeof來進行。
栗子:
console.log(typeof null); //objectconsole.log(typeof []); //objectconsole.log(typeof {}); //objectconsole.log(typeof new Date()); //objectconsole.log(typeof new Object); //objectconsole.log(typeof function(){}); //functionconsole.log(typeof alert); //functionconsole.log(typeof 1); //numberconsole.log(typeof "abc"); //stringconsole.log(typeof true); //boolean
可以看到,typeof並不能夠準確的判斷出每一種資料類型,比如null和數組等都是object類型。因此,JavaScript判斷資料類型不推薦使用typeof。
那麼要如何具體判斷呢??看一下文法<( ̄3 ̄)> !
栗子:
console.log({}.toString.call(null)); //[object Null]console.log({}.toString.call([])); //[object Array]console.log({}.toString.call({})); //[object Object]console.log({}.toString.call(new Date())); //[object Date]console.log({}.toString.call(function(){})); //[object Function]console.log({}.toString.call(new Object)); //[object Object]console.log({}.toString.call(alert)); //[object Function]console.log({}.toString.call(1)); //[object Number]console.log({}.toString.call('abc')); //[object String]console.log({}.toString.call(true)); //[object Boolean]
哈哈,是不是一目瞭然呀!!
那如果你用的是jQuery,就不用這麼麻煩嘍,可以直接用工具方法$.type(),進行判斷
栗子:
console.log($.type(null)); //nullconsole.log($.type([])); //arrayconsole.log($.type({})); //objectconsole.log($.type(1)); //number......不全寫完了,結果和{}.toString.call(obj);是一樣的
實際上{}.toString.call(obj);就是jQuery中$.type()這個工具方法的實現最重要的一段代碼(⊙o⊙)哦,神奇吧!趕快去jQuery源碼中找找看吧~~
以上就是小編為大家帶來的關於JavaScript和jQuery的類型判斷詳解全部內容了,希望大家多多支援雲棲社區~