typeof返回一個表達式的數據類型的字符串,返回結果為js基本的數據類型,包括number,boolean,string,object,undefined,function.語法為typeof(data) 或 typeof data
instanceof則為判斷一個對象是否為某一數據類型,或一個變量是否為一個對象的實例;返回boolean類型
語法為 o instanceof A
以下為綜合實例:
以下為引用的內容: <script type="text/javascript"> <!– alert("typeof(1):" + typeof(1));//number alert("typeof("abc"):" + typeof("abc"));//string alert("typeof(true):" +typeof(true));//boolean alert("typeof(2009-2-4):" + typeof(2009-2-4));//number alert("typeof("2009-2-4"):" + typeof("2009-2-4"));//string alert("typeof(m):" + typeof(m));//undefined var d=new Date(); alert("typeof(d):" + typeof(d));//object function Person(){}; alert("typeof(Person):" + typeof(Person));//function var a=new Array(); alert("typeof(a):" + typeof(a));//object alert("a instanceof Array:" + (a instanceof Array)); var h=new Person(); var o={}; alert("h instanceof Person:" + (h instanceof Person));//true alert("h instanceof Object:" + (h instanceof Object));//true alert("o instanceof Object:" + (o instanceof Object));//true alert(typeof(h));//object //–> </script> |
js中constructor較少使用,如果不是搜索到相關construtor相關的資料,我之前從沒有注意到js還有這個函數。使用typeof的一個不好的地方就是它會把Array還有用戶自定義函數都返回為object。
以下為引用的內容: <script type="text/javascript"> <!– var j=2; alert(typeof(j));//number alert("j.constructor:" + j.constructor);//function … alert(typeof(j.constructor));//function //–> </script> |
可以看到js.constructor返回的是一些字符串,大家都應該能看到這是一個function類型,此例為Number()為Number對象的構造函數,Number()用于將其參數轉換為數字number類型,并返回轉換結果(若不能轉換則返回 NaN)。
因此在以后的js判斷數據類型時可以使用以下方式來得到其詳細數據類型。
以下為引用的內容: if((typeof o=="object") && (o.constructor==Number)){ … } |
這里還要注意,constructor只能對已有變量進行判斷,而typeof則可對未聲明變量進行判斷(返回undefined)。
轉自:http://www.51obj.cn/