對于類型的判斷,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 ̄)> !
{}.toString.call(obj);栗子:
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()這個工具方法的實現(xiàn)最重要的一段代碼(⊙o⊙)哦,神奇吧!趕快去jQuery源碼中找找看吧~~
以上就是小編為大家?guī)淼年P于JavaScript和jQuery的類型判斷詳解全部內容了,希望大家多多支持武林網~
新聞熱點
疑難解答