數(shù)據(jù)類型
在JavaScript中,包含6種數(shù)據(jù)類型,字符串(string),數(shù)值(number),布爾值(boolean),undefined,null及對(duì)象(object)。
var str="Hello,world";
var i=10;
var f=2.3;
var b=true;
console.log(typeof str);//string
console.log(typeof i);number
console.log(typeof f);number
console.log(typeof b);boolean
console.log(typeof x);undefined
對(duì)象類型
對(duì)象類型是一種復(fù)合的數(shù)據(jù)類型,其基本元素由基本數(shù)據(jù)類型組成,當(dāng)然不限于基本類型,比如對(duì)象類型中的值可以是其他的對(duì)象類型實(shí)例,如下:
var str="Hello,world";
var obj=new Object();
obj.str=str;
obj.num=2.3;
var array=new Array("foo","bar","zoo");
var func=function(){
console.log("this is a Function");
};
console.log(typeof obj);//object
console.log(typeof func);//function
console.log(typeof array);//object
console.log(typeof str);//string
可以看出對(duì)象和數(shù)組的類型都是object,對(duì)象和數(shù)組的界限并不那么明顯(實(shí)際上他們屬于同一類型object)但他們的行為有所不同
類型的判斷
JavaScript是一個(gè)弱類型的語(yǔ)言,但有時(shí)候我們需要知道數(shù)據(jù)類型 ( typeof instanceof )
function handleMessage(handle,message){
return handle(message);
}
在調(diào)用handleMessage時(shí)如果傳入的handle不是函數(shù)則會(huì)報(bào)錯(cuò),因此我們有必要調(diào)用前進(jìn)行判斷
function handleMessage(handle,message){
if(typeof handle=="function"){
return handle(message);
}else{
throw new Error("handle is not a Function");
}
}
但是typeof并不是總有效,比如下面這種情況。
var obj={};
var array=[];
console.log(typeof(obj));//object
console.log(typeof(array));object
運(yùn)行結(jié)果都是object,這樣我們將無(wú)法判斷數(shù)組和對(duì)象,這時(shí)候可以通過(guò)調(diào)用instanceof來(lái)進(jìn)行判斷
console.log(obj instanceof Array);//false
console.log(array instanceof Array);//true
因此我們可以將typeof操作符和instanceof