用instanceof判斷數組類型

1.typeof用以獲取一個變量的類型,typeof通常只能返回以下幾個結果:number,boolean,string,function,object,undefined。咱們能夠使用typeof來獲取一個變量是否存在,如if(typeof a!="undefined"){},而不要去使用if(a)由於若是a不存在(未聲明)則會出錯,對於Array,Null等特殊對象使用typeof一概返回object,這正是typeof的侷限性。數組

2.若是咱們但願獲取一個對象是不是數組,或判斷某個變量是不是某個對象的實例則要選擇使用instanceofinstanceof用於判斷一個變量是否某個對象的實例,如var a=new Array();alert(a instanceof Array);會返回true,同時alert(a instanceof Object)也會返回true;這是由於Arrayobject的子類。再如:function test(){};var a=new test();alert(a instanceof test)會返回truespa

相關文章
相關標籤/搜索