一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

js 返回变量的类型代码

时间:2010-05-19 编辑:简简单单 来源:一聚教程网

本文章为你提供一款js 返回变量的类型代码哦,如果你不懂得如何获取js变量的类型的话,看看我们下面的代码你就知道如何获取js变量的代码哦。


//得到x的类型,返回类型名称
function getType(x) {
//如果x为null,则返回null
if (x == null) return "null";
var t = typeof x;
//如果x为简单类型,则返回类型名称
if (t.toLocaleLowerCase() != "object") return t;
//调用object类的toString方法得到类型信息
//object.toString方法返回类似这样的信息[object 类名]
t = Object.prototype.toString.apply(x).toLowerCase();
//截取toString方法返回值的类名部分
t = t.substring(8, t.length - 1);
if (t.toLocaleLowerCase() != "object") return t;
//检查x确实为object类型
if (x.constructor == Object) return t;
//从构造函数得到类型名称
if (typeof x.constructor == "function")
return getFunctionName(x.constructor);
return "unknow type";
}
//得到函数名称
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];
}

热门栏目