特點
typeof運算符是一個一元運算符,不是函數
用法
typeof 運算數
typeof(運算數)
返回值
返回值是字符串,全部為小寫字母
結果
'string'
'number'
'boolean'
'function'
'undefined'
'object'
原始類型
字符串、數字、布爾值分別返回'string'
、'number'
、'boolean'
var str = '123';
typeof str //'string'
var num1 = 123;
var num2 = NaN;
typeof num1 //'number'
typeof num2 //'number'
typeof true //'boolean'
typeof false //'boolean'
函數
函數返回'function'
function fn(){};
var a = function(){};
typeof fn //'function'
typeof a //'function'
undefined
undefined返回'undefined'
未聲明變量返回'undefined'
變量未聲明在使用的時候報錯,但是使用typeof運算符則是返回undefined
typeof undefined //'undefined'
typeof a //'undefined'
a //報錯 a is not defined
其他
除上述情況外,都返回'object'
typeof window //'object'
typeof document //'object'
typeof [] //'object'
typeof {} //'object'
typeof null //'object'