1.typeof
typeof 用來判斷各種數據類型,有兩種寫法:typeof xxx , typeof(xxx)
例如:
typeof 2
這里面包含了js里面的五種數據類型 number、string、boolean、 undefined、object 和函數類型 function
2. instanceof
判斷已知對象類型的方法.instanceof 后面一定要是對象類型,并且大小寫不能錯,該方法適合一些條件選擇或分支。
var c= [1,2,3]; var d = new Date(); var e = function(){alert(111);}; var f = function(){this.name="22";}; console.log(c instanceof Array) //true console.log(d instanceof Date) //true console.log(e instanceof Function) //true // console.log(f instanceof function ) //false
3.constructor
根據對象的constructor判斷,返回對創建此對象的數組函數的引用。
var c= [1,2,3]; var d = new Date(); var e = function(){alert(111);}; alert(c.constructor === Array) ----------> true alert(d.constructor === Date) -----------> true alert(e.constructor === Function) -------> true //注意: constructor 在類繼承時會出錯
4.prototype
所有數據類型均可判斷:Object.prototype.toString.call
這是對象的一個原生原型擴展函數,用來更精確的區分數據類型。
var gettype=Object.prototype.toString gettype.call('aaaa')
其實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]; } ........ }
總結
聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com