typeof一般用來獲取一個變量或者表達式的類型。
> typeof undefined
'undefined'
> typeof null // well-known bug
'object'
> typeof true
'boolean'
> typeof 123
'number'
> typeof "abc"
'string'
> typeof function() {}
'function'
> typeof {}
'object'
> typeof []
'object'
> typeof unknownVariable
'undefined'
function SuperType(){
}
console.log(typeof(SuperType)); //function
可以看到typeof一般返回值有undefined、Object(包括數組,NULL, 對象)、String、number、Boolean、function.
我們可以使用typeof來獲取一個變量是否存在,如
if(typeof a!=”undefined”){},
而不要去使用if(a)因爲如果a不存在(未聲明)則會出錯,
正因爲typeof遇到null,數組,對象時都會返回object類型,所以當我們要判斷一個對象是否是數組時
或者判斷某個變量是否是某個對象的實例則要選擇使用另一個關鍵語法instanceof.
instanceofxao操作符是一個雙目運算符。判斷一個對象是否是另一個對象的實例。
function SuperType(){
}
var instance = new Supertype();
alert(instance instanceof SuperType); //true;
alert(instance instanceof Object); //true ; 所有引用類型默認都是Object的實例
alert(instance instanceof Function); //false;
//instance是一個對象,而不是函數
alert(SuperType instanceof Function); //true ;
var a=new Array();alert(a instanceof Array); //true;