您好,欢迎访问一九零五行业门户网

JavaScript基于自定义函数判断变量类型的实现方法

本文实例讲述了javascript基于自定义函数判断变量类型的实现方法。分享给大家供大家参考,具体如下:
通常用typeof来判断js变量的类型,但很多时候仅仅typeof满足不了要求的。
我写了一个自定义函数来做这个事,判断的比较全面了。
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
其它类似信息

推荐信息