数据类型检测-typeof运算符

特点

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'
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容