萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

JavaScript typeof 運算子完整教學

用途

typeof 用於檢測值的資料型別,回傳字串。因 JS 為動態型別,此運算子為型別檢查基礎工具。

可能回傳值

回傳字串對應型別
"undefined"未定義
"boolean"布林值
"string"字串
"number"數值(含 NaN、Infinity)
"object"物件、陣列、null、Date、RegExp 等
"function"函式
"symbol"Symbol (ES6+)
"bigint"BigInt (ES2020+)

使用範例

var message = "some string";
alert(typeof message);      // "string"
alert(typeof(message));     // "string"(括號可選)
alert(typeof 95);           // "number"
alert(typeof null);         // "object" —— 知名歷史 Bug
alert(typeof []);           // "object"
alert(typeof function(){}); // "function"

注意事項

  • typeof null === "object" 是語言規格遺留的 Bug,判斷 null 請用 val === null。
  • 無法區分陣列、Date、自訂物件,需搭配 Array.isArray()、Object.prototype.toString.call() 或 instanceof。
  • typeof 是運算子而非函式,括號非必要但可加以增強可讀性。
copyright © 萬盛學電腦網 all rights reserved