javascript 得到变量类型的函数

  这个功能需要写一点代码来实现。下面的函数可以得到一个变量的类型,调用时传递一个变量进去,会返回用字符串形式描述的变量类型。

  

复制代码 代码如下:

  //得到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*function\s+([\w\$]+)\s*\(/;

  var name = reg.exec(fn);

  if (!name) {

  return '(Anonymous)';

  }

  return name[1];

  }