js的各種數(shù)據(jù)類型判斷的介紹
1.typeof
typeof 用來判斷各種數(shù)據(jù)類型,有兩種寫法: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里面的五種數(shù)據(jù)類型 number、string、boolean、 undefined、object 和函數(shù)類型 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
根據(jù)對象的constructor判斷,返回對創(chuàng)建此對象的數(shù)組函數(shù)的引用。
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
所有數(shù)據(jù)類型均可判斷:Object.prototype.toString.call
這是對象的一個原生原型擴展函數(shù),用來更精確的區(qū)分數(shù)據(jù)類型。
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節(jié)點的判斷,這些東西在我們寫插件的時候都會用到。
可以封裝的方法如下:
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]; } ........ }
總結
以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學習或者工作具有一定的參考學習價值,謝謝大家對腳本之家的支持。如果你想了解更多相關內(nèi)容請查看下面相關鏈接
相關文章
JS 頁面內(nèi)容搜索,類似于 Ctrl+F功能的實現(xiàn)代碼
JS 頁面內(nèi)容搜索,類似于 Ctrl+F功能的實現(xiàn)代碼...2007-08-08Javascript的異步函數(shù)和Promise對象你了解嗎
這篇文章主要為大家詳細介紹了Javascript異步函數(shù)和Promise對象,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下,希望能夠給你帶來幫助2022-03-03easywasmplayer實現(xiàn)視頻流播放示例詳解
這篇文章主要為大家介紹了easywasmplayer實現(xiàn)視頻流播放示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-09-09JavaScript實現(xiàn)函數(shù)重載的代碼示例
在JavaScript中并沒有直接支持函數(shù)重載的機制,但是可以通過一些技巧來模擬函數(shù)重載的效果,比如使用參數(shù)判斷,使用默認參數(shù),對象參數(shù),這些方法都可以實現(xiàn)類似函數(shù)重載的效果,所以本文就給大家介紹一下JavaScript如何實現(xiàn)函數(shù)重載,需要的朋友可以參考下2023-08-08深入學習js函數(shù)的隱式參數(shù) arguments 和 this
這篇文章主要介紹了 深入學習js函數(shù)的隱式參數(shù) arguments 和 this,arguments是一個類數(shù)組結構,它保存了調(diào)用時傳遞給函數(shù)的所有實參;this是函數(shù)執(zhí)行時的上下文對象, 這個對象有些讓人感到困惑的行為。 下面分別對他們進行討論。,需要的朋友可以參考下2019-06-06