写javascirpt代码时,typeof和instanceof这两个操作符时不时就会用到,堪称必用。但是!使用它们总是不能直接的得到想要的结果,非常纠结,普遍的说法认为“这两个操作符或许是javascript中最大的设计缺陷,因为几乎不可能从他们那里得到想要的结果”
typeof
说明:typeof返回一个表达式的数据类型的字符串,返回结果为js基本的数据类型,包括number,boolean,string,object,undefined,function。
从说明来看,貌似没什么问题。
下面的代码写了一个数值变量,typeof后的结果是"number"。
复制代码 代码如下:
var a = 1;
console.log(typeof(a)); //=>number
复制代码 代码如下:
var a = new Number(1);
console.log(typeof(a)); //=>object
复制代码 代码如下:
var a = 1;
var b = new Number(1);
复制代码 代码如下:
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));
复制代码 代码如下:
function is(obj,type) {
var clas = Object.prototype.toString.call(obj).slice(8, -1);
return obj !== undefined && obj !== null && clas === type;
}
复制代码 代码如下:
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
复制代码 代码如下:
console.log("abc" instanceof String); // false
console.log("abc" instanceof Object); // false
console.log(new String("abc") instanceof String); // true
console.log(new String("abc") instanceof Object); // true
复制代码 代码如下:
function Person() {}
function Man() {}
Man.prototype = new Person();
console.log(new Man() instanceof Man); // true
console.log(new Man() instanceof Person); // true
新闻热点
疑难解答
图片精选