寫javascirpt代碼時(shí),typeof和instanceof這兩個(gè)操作符時(shí)不時(shí)就會(huì)用到,堪稱必用。但是!使用它們總是不能直接的得到想要的結(jié)果,非常糾結(jié),普遍的說法認(rèn)為“這兩個(gè)操作符或許是javascript中最大的設(shè)計(jì)缺陷,因?yàn)閹缀醪豢赡軓乃麄兡抢锏玫较胍慕Y(jié)果”
typeof
說明:typeof返回一個(gè)表達(dá)式的數(shù)據(jù)類型的字符串,返回結(jié)果為js基本的數(shù)據(jù)類型,包括number,boolean,string,object,undefined,function。
從說明來看,貌似沒什么問題。
下面的代碼寫了一個(gè)數(shù)值變量,typeof后的結(jié)果是"number"。
復(fù)制代碼 代碼如下:
var a = 1;
console.log(typeof(a)); //=>number
復(fù)制代碼 代碼如下:
var a = new Number(1);
console.log(typeof(a)); //=>object
復(fù)制代碼 代碼如下:
var a = 1;
var b = new Number(1);
復(fù)制代碼 代碼如下:
var a = 1;
var b = new Number(1);
console.log(Object.prototype.toString.call(a));
console.log(Object.prototype.toString.call(b));
復(fù)制代碼 代碼如下:
[object Number]
[object Number]
復(fù)制代碼 代碼如下:
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));
復(fù)制代碼 代碼如下:
function is(obj,type) {
var clas = Object.prototype.toString.call(obj).slice(8, -1);
return obj !== undefined && obj !== null && clas === type;
}
復(fù)制代碼 代碼如下:
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
復(fù)制代碼 代碼如下:
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
復(fù)制代碼 代碼如下:
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
復(fù)制代碼 代碼如下:
function Person() {}
function Man() {}
Man.prototype = new Person();
console.log(new Man() instanceof Man); // true
console.log(new Man() instanceof Person); // true
新聞熱點(diǎn)
疑難解答
圖片精選