最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

js的各種數(shù)據(jù)類型判斷的介紹

 更新時(shí)間:2019年01月19日 09:25:58   作者:muzidigbig  
今天小編就為大家分享一篇關(guān)于js的各種數(shù)據(jù)類型判斷的介紹,小編覺得內(nèi)容挺不錯(cuò)的,現(xiàn)在分享給大家,具有很好的參考價(jià)值,需要的朋友一起跟隨小編來看看吧

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 后面一定要是對象類型,并且大小寫不能錯(cuò),該方法適合一些條件選擇或分支。

  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 在類繼承時(shí)會出錯(cuò)

4.prototype

所有數(shù)據(jù)類型均可判斷:Object.prototype.toString.call

這是對象的一個(gè)原生原型擴(kuò)展函數(shù),用來更精確的區(qū)分?jǐn)?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]

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

可以封裝的方法如下:

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

總結(jié)

以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,謝謝大家對腳本之家的支持。如果你想了解更多相關(guān)內(nèi)容請查看下面相關(guān)鏈接

相關(guān)文章

最新評論

福海县| 隆尧县| 阳东县| 广州市| 玉屏| 大同市| 饶平县| 宜兴市| 鹤山市| 平江县| 绍兴县| 岳普湖县| 三都| 华阴市| 宽城| 高清| 富阳市| 富平县| 东兰县| 无为县| 府谷县| 安丘市| 九龙县| 大邑县| 济源市| 饶阳县| 运城市| 云霄县| 桂林市| 都安| 樟树市| 泗洪县| 普兰县| 体育| 红安县| 浦县| 于都县| 高雄市| 巨鹿县| 沛县| 沽源县|