JavaScript基于自定義函數(shù)判斷變量類型的實現(xiàn)方法
更新時間:2016年11月23日 10:47:29 作者:cuixiping
這篇文章主要介紹了JavaScript基于自定義函數(shù)判斷變量類型的實現(xiàn)方法,結合實例形式分析了javascript判斷變量類型的自定義函數(shù)定義與使用方法,并針對不同瀏覽器給出了相關的分析與說明,需要的朋友可以參考下
本文實例講述了JavaScript基于自定義函數(shù)判斷變量類型的實現(xiàn)方法。分享給大家供大家參考,具體如下:
通常用typeof來判斷js變量的類型,但很多時候僅僅typeof滿足不了要求的。
我寫了一個自定義函數(shù)來做這個事,判斷的比較全面了。
function varType(v){
if ( typeof v=== "object" ){
if (v=== null ) return 'null' ;
if (v. constructor )
return (v. constructor .toString()).match(/(?: )[/w/$]+/)[ 0 ];
if ( typeof typeof2=== 'undefined' && window .execScript){
window .execScript( 'Function vbsTypeName(o):vbsTypeName=TypeName(o):End Function' , 'vbscript' );
window .execScript( 'function typeof2(o){return vbsTypeName(o)}' , 'jscript' );
}
if ( typeof typeof2!== 'undefined' ){
return typeof2(v);
}
return "object" ;
}
return typeof v;
}
//對于普通js常量和js對象,各瀏覽器是基本一致的
alert (varType()); //undefined
alert (varType( 100 )); //number
alert (varType({})); //Object
alert (varType([])); //Array
alert (varType(/ /)); //RegExp
alert (varType( new Date ())); //Date
alert (varType( Date )); //function
alert (varType( Object )); //function
alert (varType( RegExp )); //function
//對于DOM對象,各瀏覽器可能會有不同值
alert (varType( window )); //IE:HTMLWindow2 FF:Window
alert (varType( document )); //IE:HTMLDocument FF:HTMLDocument
alert (varType( document .body)); //IE:HTMLBody FF:HTMLBodyElement
alert (varType( Option )); //IE:Object FF:function
alert (varType( Image )); //IE:Object FF:function
alert (varType( navigator )); //IE:DispHTMLNavigator FF:Navigator
//以下幾個只適用于IE,其他內核瀏覽器不支持
alert (varType( ActiveXObject )); //IE:function
alert (varType( Enumerator )); //IE:function
alert (varType( new ActiveXObject ( "Scripting.Dictionary" ))); //IE:Dictionary
alert (varType( new Enumerator ())); //IE:Enumerator
更多關于JavaScript相關內容感興趣的讀者可查看本站專題:《JavaScript數(shù)學運算用法總結》、《JavaScript查找算法技巧總結》、《JavaScript錯誤與調試技巧總結》、《JavaScript數(shù)據(jù)結構與算法技巧總結》及《JavaScript遍歷算法與技巧總結》
希望本文所述對大家JavaScript程序設計有所幫助。
相關文章
JS中判斷JSON數(shù)據(jù)是否存在某字段的方法
這篇文章主要介紹了JS中如何判斷JSON數(shù)據(jù)是否存在某字段,需要的朋友可以參考下2014-03-03
JavaScript?Canvas繪制六邊形網(wǎng)格
這篇文章主要為大家詳細介紹了JavaScript?Canvas繪制六邊形網(wǎng)格,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2022-01-01

