該文章轉自http://blog.csdn.net/cuixiping/archive/2009/07/11/4340933.aspx
首先,typeof是一個一元運算子(就像++,--,!,- 等一元運算子),不是一個函數,也不是一個語句。
這個辨析很必要,初學者往往以為它是一個函數,因為它經常被以typeof(abc)類似的形式使用,所以貌似函數。
但可以 var b = (typeof abc=="undefined") 這樣用就說明了它不是函數(js裡面函數執行要跟括弧的)也不是語句(語句就不能再和後面的值進行==比較了)
typeof運算子介紹:
typeof 是一個一元運算子,放在一個運算數之前,運算數可以是任意類型。
它傳回值是一個字串,該字串說明運算數的類型。
你知道下面typeof運算的結果嗎?
typeof(1);
typeof(NaN);
typeof(Number.MIN_VALUE);
typeof(Infinity);
typeof("123");
typeof(true);
typeof(window);
typeof(document);
typeof(null);
typeof(eval);
typeof(Date);
typeof(sss);
typeof(undefined);
看看你會幾個?
如果看了以後,不是很明白的話,請看下面(明白的人就不用往下看了):
typeof是一個一元運算子,它返回的結果始終是一個字串,對不同的運算元,它返回不同的結果。
具體的規則如下:
一、對於數字類型的運算元而言, typeof 返回的值是 number。比如說:typeof(1),返回的值就是number。
上面是舉的常規數字,對於非常規的數字類型而言,其結果返回的也是number。比如typeof(NaN),NaN在
JavaScript中代表的是特殊非數字值,雖然它本身是一個數字類型。
在JavaScript中,特殊的數字類型還有幾種:
Infinity 表示無窮大特殊值
NaN 特殊的非數字值
Number.MAX_VALUE 可表示的最大數字
Number.MIN_VALUE 可表示的最小數字(與零最接近)
Number.NaN 特殊的非數字值
Number.POSITIVE_INFINITY 表示正無窮大的特殊值
Number.NEGATIVE_INFINITY 表示負無窮大的特殊值
以上特殊類型,在用typeof進行運算進,其結果都將是number。
二、對於字串類型, typeof 返回的值是 string。比如typeof("123")返回的值是string。
三、對於布爾類型, typeof 返回的值是 boolean 。比如typeof(true)返回的值是boolean。
四、對於對象、數組、null 返回的值是 object 。比如typeof(window),typeof(document),typeof(null)返回的值都是object。
五、對於函數類型,返回的值是 function。比如:typeof(eval),typeof(Date)返回的值都是function。
六、如果運算數是沒有定義的(比如說不存在的變數、函數或者undefined),將返回undefined。比如:typeof(sss)、typeof(undefined)都返回undefined。
看完了六條規則,再回頭看一下,是不是很簡單了……
下面我們將用程式碼驗證一下:
document.write ("typeof(1): "+typeof(1)+"<br>");<br />document.write ("typeof(NaN): "+typeof(NaN)+"<br>");<br />document.write ("typeof(Number.MIN_VALUE): "+typeof(Number.MIN_VALUE)+"<br>")<br />document.write ("typeof(Infinity): "+typeof(Infinity)+"<br>")<br />document.write ("typeof(/"123/"): "+typeof("123")+"<br>")<br />document.write ("typeof(true): "+typeof(true)+"<br>")<br />document.write ("typeof(window): "+typeof(window)+"<br>")<br />document.write ("typeof(document): "+typeof(document)+"<br>")<br />document.write ("typeof(null): "+typeof(null)+"<br>")<br />document.write ("typeof(eval): "+typeof(eval)+"<br>")<br />document.write ("typeof(Date): "+typeof(Date)+"<br>")<br />document.write ("typeof(sss): "+typeof(sss)+"<br>")<br />document.write ("typeof(undefined): "+typeof(undefined)+"<br>")