In JavaScript, you sometimes need to know the type of a variable accurately. Obviously, the typeof function cannot meet this requirement. In most cases, this function returns an object. This function requires a bit of code to implement. The following function can get a variable type. When you call a variable, a variable type described in the string format will be returned.
The Code is as follows:
// Obtain the type of x, and return the type name.
Function getType (x ){
// If x is null, null is returned.
If (x = null) return "null ";
Var t = typeof x;
// If x is a simple type, the return type name
If (t. toLocaleLowerCase ()! = "Object") return t;
// Call the toString method of the object class to obtain the type information.
// The object. toString method returns information similar to this [object class name]
T = Object. prototype. toString. apply (x). toLowerCase ();
// Intercept the class name part returned by the toString Method
T = t. substring (8, t. length-1 );
If (t. toLocaleLowerCase ()! = "Object") return t;
// Check whether x is of the object Type
If (x. constructor = Object) return t;
// Obtain the type name from the constructor
If (typeof x. constructor = "function ")
Return getFunctionName (x. constructor );
Return "unknow type ";
}
// Obtain the function name
Function getFunctionName (fn ){
If (typeof fn! = "Function") throw "the argument must be a function .";
Var reg =/\ W * function \ s + ([\ w \ $] +) \ s *\(/;
Var name = reg.exe c (fn );
If (! Name ){
Return '(Anonymous )';
}
Return name [1];
}