获取类型信息: 复制代码 代码如下: var a = 1; var b = new Number(1); console.log(Object.prototype.toString.call(a)); console.log(Object.prototype.toString.call(b));
输出: 复制代码 代码如下: [object Number] [object Number]
是不是已经很直接了,我们稍微处理一下,得到直接结果: 复制代码 代码如下: var a = 1; var b = new Number(1); console.log(Object.prototype.toString.call(a).slice(8,-1)); console.log(Object.prototype.toString.call(b).slice(8,-1));
输出: Number Number 这就是想要的结果。 为了更好的使用,我们封装一个方法,用来判断某个变量是否是某种类型: 复制代码 代码如下: function is(obj,type) { var clas = Object.prototype.toString.call(obj).slice(8, -1); return obj !== undefined && obj !== null && clas === type; }
定义一些变量做过测试,先来看看它们的typeof输出: 复制代码 代码如下: var a1=1; var a2=Number(1); var b1="hello"; var b2=new String("hello"); var c1=[1,2,3]; var c2=new Array(1,2,3); console.log("a1"s typeof:"+typeof(a1)); console.log("a2"s typeof:"+typeof(a2)); console.log("b1"s typeof:"+typeof(b1)); console.log("b2"s typeof:"+typeof(b2)); console.log("c1"s typeof:"+typeof(c1)); console.log("c2"s typeof:"+typeof(c2)); 输出: a1"s typeof:number a2"s typeof:object b1"s typeof:string b2"s typeof:object c1"s typeof:object c2"s typeof:object
我们再用新作的函数是一下: 复制代码 代码如下: console.log("a1 is Number:"+is(a1,"Number")); console.log("a2 is Number:"+is(a2,"Number")); console.log("b1 is String:"+is(b1,"String")); console.log("b2 is String:"+is(b2,"String")); console.log("c1 is Array:"+is(c1,"Array")); console.log("c2 is Array:"+is(c2,"Array")); 输出: a1 is Number:true a2 is Number:true b1 is String:true b2 is String:true c1 is Array:true c2 is Array:true