typeof操作符在JavaScript中用于檢測變量的數據類型,它能識別的基本類型包括:1.”number”、2.”String”、3.”Boolean”、4.”undefined”、5.”Object”(含NULL)、6.”function”、7.”symbol”、8.”bigint”;但需要注意typeof null返回”object”是歷史問題,并不代表null是對象;判斷數組應使用Array.isarray(),更復雜的對象類型建議用object.prototype.tostring.call()來判斷。
在JavaScript中,typeof 是一個常用的操作符,用來檢測變量的數據類型。它能識別一些基本數據類型,但也有局限性。下面我們就來看看它的使用方法和適用范圍。
typeof 能檢測哪些類型?
typeof 主要用于判斷 JavaScript 中的基本數據類型,包括以下幾種:
- “number”:數字類型,如 42 或 3.14
- “string”:字符串類型,如 “hello”
- “boolean”:布爾值,如 true 或 false
- “undefined”:未定義的變量
- “object”:對象類型(注意:null 也會返回 “object”)
- “function”:函數
- “symbol”:es6 引入的 Symbol 類型
- “bigint”:ES2020 新增的大整數類型
需要注意的是,typeof null 返回的是 “object”,這是一個歷史遺留問題,并不代表 null 就是對象。
常見用法與建議
使用 typeof 非常簡單,只需要在操作符后面加上一個變量或值即可:
console.log(typeof 123); // "number" console.log(typeof 'abc'); // "string" console.log(typeof true); // "boolean" console.log(typeof undefined); // "undefined" console.log(typeof { }); // "object" console.log(typeof function(){}); // "function" console.log(typeof Symbol()); // "symbol" console.log(typeof 9007199254740991n); // "bigint"
有幾個使用時要注意的點:
- 判斷是否為數組時不能依賴 typeof,因為它會返回 “object”,應該使用 Array.isArray()。
- 檢查 null 時要單獨處理,因為 typeof null === “object”。
- 對于基本類型來說,typeof 很好用;但對復雜結構(比如數組、日期等)就不夠用了。
使用場景舉例
-
調試時快速查看變量類型
console.log(typeof userInput);
這樣可以快速知道用戶輸入的是字符串還是數字。
-
防止程序出錯 在調用某個函數前檢查參數是不是函數:
if (typeof callback === 'function') { callback(); }
-
處理不同類型的輸入邏輯
function processInput(value) { if (typeof value === 'number') { console.log('你輸入了一個數字'); } else if (typeof value === 'string') { console.log('你輸入了一個字符串'); } }
不過,如果需要更精確地判斷對象類型(例如判斷是否為 date、regexp 等),建議使用 Object.prototype.toString.call()。
基本上就這些了。typeof 不復雜但容易忽略細節,尤其在處理 null 和數組時要特別小心。