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。Array.isArray()、Object.prototype.toString.call() 或 instanceof。typeof 是運算子而非函式,括號非必要但可加以增強可讀性。