數(shù)據(jù)類型

數(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

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容