一、typeof運算符介紹:
1. 對於數字類型的操作數而言, 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。
2. 對於字符串類型, typeof 返回的值是 string。比如typeof("123")返回的值是string。
3. 對於布爾類型, typeof 返回的值是 boolean 。比如typeof(true)返回的值是boolean。
4. 對於對象、數組、null 返回的值是 object 。比如typeof(window),typeof(document),typeof(null)返回的值都是object。
5. 對於函數類型,返回的值是 function。比如:typeof(eval),typeof(Date)返回的值都是function。
6. 如果運算數是沒有定義的(比如說不存在的變量、函數或者undefined),將返回undefined。比如:typeof(sss)、typeof(undefined)都返回undefined。
<script>
console.log("typeof(1): "+typeof(1));
console.log("typeof(NaN): "+typeof(NaN));
console.log("typeof(Number.MIN_VALUE): "+typeof(Number.MIN_VALUE));
console.log("typeof(Infinity): "+typeof(Infinity));
console.log("typeof(\"123\"): "+typeof("123"));
console.log("typeof(true): "+typeof(true));
console.log("typeof(window): "+typeof(window));
console.log("typeof(document): "+typeof(document));
console.log("typeof(null): "+typeof(null));
console.log("typeof(eval): "+typeof(eval));
console.log("typeof(Date): "+typeof(Date));
console.log("typeof(sss): "+typeof(sss));
console.log("typeof(undefined): "+typeof(undefined));
</script>
運行結果如下所示: