Home >Web Front-end >JS Tutorial >javascript function to get variable type_javascript skills

javascript function to get variable type_javascript skills

WBOY
WBOYOriginal
2016-05-16 18:26:541127browse

This function requires writing a little code to implement. The following function can get the type of a variable. When calling, pass a variable in and it will return the variable type described in string form.

Copy code The code is as follows:

//Get the type of x and return the type name
function getType(x) {
//If x is null, return null
if (x == null) return "null";
var t = typeof x;
//If 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 get the type information
//object.toString The method returns information similar to this [object class name]
t = Object.prototype.toString.apply(x).toLowerCase();
//Intercept the class name part of the return value of the toString method
t = t.substring(8, t.length - 1);
if (t.toLocaleLowerCase() != "object") return t;
//Check that x is indeed object type
if (x. constructor == Object) return t;
//Get the type name from the constructor
if (typeof x.constructor == "function")
return getFunctionName(x.constructor);
return " unknow type";
}
//Get the function name
function getFunctionName(fn) {
if (typeof fn != "function") throw "the argument must be a function.";
var reg = /W*functions ([w$] )s*(/;
var name = reg.exec(fn);
if (!name) {
return '(Anonymous) ';
}
return name[1];
}
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn