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

相關文章
相關標籤/搜索