国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 語言 > JavaScript > 正文

js的各種數據類型判斷的介紹

2024-05-06 15:43:05
字體:
來源:轉載
供稿:網友

1.typeof

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

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.toStringgettype.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];   }   ........ }

總結

以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,謝謝大家對錯新站長站的支持。如果你想了解更多相關內容請查看下面相關鏈接

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表

圖片精選

主站蜘蛛池模板: 宜章县| 林周县| 南部县| 揭西县| 龙井市| 阳新县| 禹城市| 阜新市| 宜川县| 苏尼特左旗| 广南县| 赞皇县| 津南区| 邻水| 义马市| 新密市| 英吉沙县| 蕉岭县| 武穴市| 锡林浩特市| 谢通门县| 新巴尔虎左旗| 松阳县| 偃师市| 霸州市| 石嘴山市| 霍邱县| 四子王旗| 达孜县| 成都市| 武胜县| 青州市| 百色市| 钟山县| 普陀区| 囊谦县| 道孚县| 贺兰县| 白水县| 井陉县| 山东|