js typeof的運用

瞭解js的都知道, 有個typeof  用來判斷各種數據類型,有兩種寫法:typeof   xxx   ,typeof(xxx)

       如下實例:

       typeof   2      輸出   number
       typeof   null   輸出   object

       typeof   {}    輸出   object

       typeof    []    輸出   object

       typeof   (function(){})   輸出  function

       typeof    undefined         輸出  undefined

       typeof   '222'                 輸出    string

      typeof  true                   輸出     boolean

    這裏麪包含了js裏面的五種數據類型  number   string    boolean   undefined     object和函數類型 function

     看到這裏你肯定會問了:我怎麼去區分對象,數組和null呢?

     接下來我們就用到另外一個利器:Object.prototype.toString.call

     這是對象的一個原生原型擴展函數,用來更精確的區分數據類型。

     我們來試試這個玩兒意兒:

     var   gettype=Object.prototype.toString

        gettype.call('aaaa')        輸出      [object String]

        gettype.call(2222)         輸出      [object Number]

        gettype.call(true)          輸出      [object Boolean]

        gettype.call(undefined)  輸出      [object Undefined]

        gettype.call(null)                  輸出   [object Null]

         gettype.call({})                   輸出   [object Object]

         gettype.call([])                    輸出   [object Array]
         gettype.call(function(){})     輸出   [object Function]

      看到這裏,剛纔的問題我們解決了。 

      其實js 裏面還有好多類型判斷      [object HTMLDivElement]     div 對象  ,    [object HTMLBodyElement]  body 對象    ,[object Document](IE)或者  [object HTMLDocument](firefox,google) ......各種dom節點的判斷,這些東西在我們寫插件的時候都會用到。

     可以封裝的方法如下  :

      var   gettype=Object.prototype.toString

     var    utility={

          isObj:function(o){

               return    gettype.call(o)=="[object Object]";

          },

          isArray:function(o){

               return    gettype.call(o)=="[object Array]";

          },

          isNULL:function(o){

               return    gettype.call(o)=="[object Null]";

          },

          isDocument:function(){

                return    gettype.call(o)=="[object Document]"|| [object HTMLDocument];

          }

          ........

    }

 

轉載出處: http://www.cnblogs.com/a546558309/p/3608194.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章