標籤:style blog http io ar color os 使用 sp
詳解js中typeof、instanceof與constructor
typeof返回一個運算式的資料類型的字串,返回結果為js基本的資料類型,包括number,boolean,string,object,undefined,function.文法為typeof(data) 或 typeof data
instanceof則為判斷一個對象是否為某一資料類型,或一個變數是否為一個對象的執行個體;返回boolean類型
文法為 o instanceof A
以下為綜合執行個體:
1<script type="text/javascript">
2<!–
3alert("typeof(1):" + typeof(1));//number
4alert("typeof(\"abc\"):" + typeof("abc"));//string
5alert("typeof(true):" +typeof(true));//boolean
6alert("typeof(2009-2-4):" + typeof(2009-2-4));//number
7alert("typeof(\"2009-2-4\"):" + typeof("2009-2-4"));//string
8alert("typeof(m):" + typeof(m));//undefined
9var d=new Date();
10alert("typeof(d):" + typeof(d));//object
11function Person(){};
12alert("typeof(Person):" + typeof(Person));//function
13var a=new Array();
14alert("typeof(a):" + typeof(a));//object
15alert("a instanceof Array:" + (a instanceof Array));
16var h=new Person();17var o={};18alert("h instanceof Person:" + (h instanceof Person));//true19alert("h instanceof Object:" + (h instanceof Object));//true20alert("o instanceof Object:" + (o instanceof Object));//true21alert(typeof(h));//object22//–>23</script>
查看效果
js中constructor較少使用,如果不是搜尋到相關construtor相關的資料,我之前從沒有注意到js還有這個函數。
使用typeof的一個不好的地方就是它會把Array還有使用者自訂函數都返回為object
1<script type="text/javascript">
2<!–
3var j=2;
4alert(typeof(j));//number
5alert("j.constructor:" + j.constructor);//function …
6alert(typeof(j.constructor));//function
7//–>
8</script>
查看示範
可以看到js.constructor返回的是一些字串,大家都應該能看到這是一個function類型,此例為Number()為Number對象的建構函式,Number()用於將其參數轉換為數字number類型,並返迴轉換結果(若不能轉換則返回 NaN)。
因此在以後的js判斷資料類型時可以使用以下方式來得到其詳細資料類型
1if((typeof o=="object") && (o.constructor==Number)){
2…
3}
這裡還要注意,constructor只能對已有變數進行判斷,而typeof則可對未聲明變數進行判斷(返回undefined)。
原文來自:http://www.51obj.cn/
詳解js中typeof、instanceof與constructor