typeof 运算符

typeof 运算符

语法: ()可选

typeof[(]expression[)]express

返回值(6种):

  • number: 如下两种都返回number数组

    • 常规数字函数

    • 特殊的数字类型测试

      • Infinity: 表示无穷大code

      • NaN: 特殊的非数字值对象

      • Number.MAX_VALUE: 最大数字字符串

      • Number.MIN_VALUE: 最小数字(与零最接近)string

      • Number.NaN: 非数字值it

      • Number.POSITIVE_INFINITY: 正无穷大io

      • Number.NEGATIVE_INFINITY: 负无穷大

  • string
    字符串

  • boolean
    布尔值(true, false)

  • object

    • 对象: 好比window, {}, ....

    • 数组

    • null

  • function: 函数

typeof(eval) === 'funtion' // true
  typeof(Date) === 'funtion' // true
  • undefined: 未定义,好比不存在的变量、函数或者undefined
    typeof(undefined)

常见用法

  • 测试变量的数据类型

  • 判断一个变量是否存在

常见于if判断
错误写法:

// 若是a不存在(未声明)则会出错
if (a) {
  ...
}
// Uncaught ReferenceError: a is not defined
正确写法:
if (typeof a === 'undefined') {
  ...
}

还常见于三元表达式中

closable = typeof closable === 'undefined' ? true : closable;

局限性

Array, Null等特殊对象使用typeof一概返回object

相关文章
相关标签/搜索