typeof 运算符

typeof 运算符

语法: ()可选

typeof[(]expression[)]

返回值(6种):

  • number: 以下两种都返回number

    • 通例数字

    • 特别的数字范例

      • Infinity: 示意无穷大

      • NaN: 特别的非数字值

      • Number.MAX_VALUE: 最大数字

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

      • Number.NaN: 非数字值

      • Number.POSITIVE_INFINITY: 正无穷大

      • 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

    原文作者:Joeny
    原文地址: https://segmentfault.com/a/1190000010034316
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞