在 JavaScript 中,數據類型檢測是開發中的常見需求。以下是主要檢測方法及其優缺點:
1. typeof 操作符
最基礎的檢測方式,返回類型字符串:
typeof 42; // "number"
typeof "hello"; // "string"
typeof true; // "boolean"
typeof undefined; // "undefined"
typeof function() {}; // "function"
typeof Symbol(); // "symbol"
typeof {}; // "object"
typeof []; // "object" (注意!)
typeof null; // "object" (歷史遺留問題)
缺點:
- 無法區分數組、對象、null(都返回 “object”)
2. instanceof 操作符
檢測對象是否屬于某個構造函數的實例:
[] instanceof Array; // true
{} instanceof Object; // true
new Date() instanceof Date; // truefunction Person() {}
const p = new Person();
p instanceof Person; // true
缺點:
- 不適用于原始值類型(數字、字符串等)
- 多窗口/iframe 環境下失效(不同全局環境)
3. Object.prototype.toString.call()
最可靠的檢測方法,返回 [object Type] 格式:
Object.prototype.toString.call(42); // "[object Number]"
Object.prototype.toString.call("hello"); // "[object String]"
Object.prototype.toString.call([]); // "[object Array]"
Object.prototype.toString.call(null); // "[object Null]"
Object.prototype.toString.call(undefined); // "[object Undefined]"
Object.prototype.toString.call(/regex/); // "[object RegExp]"
封裝工具函數:
function getType(obj) {return Object.prototype.toString.call(obj).slice(8, -1).toLowerCase();
}getType([]); // "array"
getType(null); // "null"
4. 特殊類型檢測
- 數組檢測:
Array.isArray([]); // true (ES5+ 最佳方案)
// 舊瀏覽器兼容方案:
Object.prototype.toString.call([]) === "[object Array]";
- NaN 檢測:
isNaN(NaN); // true (注意: isNaN("abc") 也返回 true)
Number.isNaN(NaN); // true (ES6 推薦,嚴格檢測)
- null/undefined 檢測:
let foo = null;
foo === null; // true (精確檢測 null)
typeof bar === "undefined"; // 檢測未定義
終極解決方案
結合多種方式實現全類型檢測:
function detectType(value) {// 處理 null 和 undefinedif (value === null) return "null";if (value === undefined) return "undefined";// 處理其他類型const type = typeof value;if (type !== "object") return type; // 原始類型直接返回// 對象類型細化return Object.prototype.toString.call(value).slice(8, -1).toLowerCase();
}// 測試
detectType([]); // "array"
detectType(new Map()); // "map"
detectType(Symbol()); // "symbol"
detectType(42); // "number"
總結對比
方法 | 優點 | 缺點 |
---|---|---|
typeof | 簡單快速,適合原始類型 | 無法區分數組/對象/null |
instanceof | 檢測自定義對象 | 不適用原始類型,多窗口環境失效 |
Object.prototype.toString | 精準識別所有類型(推薦) | 語法稍復雜 |
Array.isArray() | 數組檢測最優解 | 僅適用于數組 |
最佳實踐:
- 基礎類型檢測 → typeof
- 數組檢測 → Array.isArray()
- 完整類型檢測 → Object.prototype.toString.call()
- null 檢測 → value === null