SoFunction
Updated on 2025-04-08

JavaScript implementation method for judging variable types based on custom functions

This article describes the implementation method of JavaScript to judge variable types based on custom functions. Share it for your reference, as follows:

Typeof is usually used to judge the type of js variables, but often only typeof cannot meet the requirements.

I wrote a custom function to do this, and my judgment was relatively comprehensive.

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;
}
//For ordinary js constants and js objects, each browser is basically the samealert (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
//For DOM objects, each browser may have different valuesalert (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
//The following are only applicable to IE, and other kernel browsers do not support italert (varType( ActiveXObject )); //IE:function
alert (varType( Enumerator )); //IE:function
alert (varType( new ActiveXObject ( "" ))); //IE:Dictionary
alert (varType( new Enumerator ())); //IE:Enumerator

For more information about JavaScript, readers who are interested in reading this site's special topic:Summary of JavaScript mathematical operations usage》、《Summary of JavaScript search algorithm skills》、《Summary of JavaScript Errors and Debugging Skills》、《Summary of JavaScript data structure and algorithm techniques"and"Summary of JavaScript traversal algorithm and skills

I hope this article will be helpful to everyone's JavaScript programming.