首頁  >  文章  >  web前端  >  關於javascript判斷資料類型的方法實例總結

關於javascript判斷資料類型的方法實例總結

伊谢尔伦
伊谢尔伦原創
2017-07-18 09:23:031086瀏覽

js裡麵包含五種資料型別  number   string    boolean   undefinedobject和函數型別function

有這裡你一定會問了:我怎麼去區分對象,陣列與null呢?

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

這是物件的一個原生原型擴充函數,用來更精確的區分資料類型。

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

var   gettype=Object.prototype.toString

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

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

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

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

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

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

#看到這裡,剛才的問題我們解決了。

其實js 裡面還有好多型別判斷 

[object HTMLpElement]   p 物件,    [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];
     }
     ........
}

1 判斷是否為陣列型別 

<script type="text/javascript"> 
//<![CDATA[ 
var a=[0]; 
document.write(isArray(a),&#39;<br/>&#39;); 
function isArray(obj){ 
return (typeof obj==&#39;object&#39;)&&obj.constructor==Array; 
} 
//]]> 
</script>

2 判斷是否為字串型別 

<script type="text/javascript"> 
//<![CDATA[ 
document.write(isString(&#39;test&#39;),&#39;<br/>&#39;); 
document.write(isString(10),&#39;<br/>&#39;); 
function isString(str){ 
return (typeof str==&#39;string&#39;)&&str.constructor==String; 
} 
//]]> 
</script>

3 判斷是否為數值型別 

<script type="text/javascript"> 
//<![CDATA[ 
document.write(isNumber(&#39;test&#39;),&#39;<br/>&#39;); 
document.write(isNumber(10),&#39;<br/>&#39;); 
function isNumber(obj){ 
return (typeof obj==&#39;number&#39;)&&obj.constructor==Number; 
} 
//]]> 
</script>

以上是關於javascript判斷資料類型的方法實例總結的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn