typeof 是一元運算符,返回字符串表示操作數的類型。它是 JS 中最基礎的類型檢測工具,但存在著名的 typeof null === 'object' 等陷阱。本文系統整理返回值對照表、判斷邏輯、常見誤區與更精準的替代方案。
typeof operand
typeof (operand) // 帶括號亦可,視為運算符而非函數
| 類型 | 返回值 | 示例 |
|---|---|---|
| Undefined | "undefined" | typeof undefined |
| Null | "object" | typeof null ← 著名 Bug |
| Boolean | "boolean" | typeof true |
| Number | "number" | typeof 123 / typeof NaN / typeof Infinity |
| BigInt | "bigint" | typeof 9007199254740991n |
| String | "string" | typeof "abc" |
| Symbol | "symbol" | typeof Symbol() |
| Function | "function" | typeof function(){} / typeof alert |
| Object (含 Array, Date, RegExp, 普通對象) | "object" | typeof {} / typeof [] / typeof new Date() |
val === null。function getType(val) {
return Object.prototype.toString.call(val).slice(8, -1).toLowerCase();
// 返回: "number", "string", "boolean", "undefined", "null", "array", "object", "date", "regexp", "function", "error", "symbol", "bigint", "map", "set", ...
}
getType(null); // "null"
getType([]); // "array"
getType(new Date()); // "date"
getType(/abc/); // "regexp"
getType(function(){}); // "function"
Array.isArray([]) // true
Array.isArray({}) // false
Number.isNaN(NaN) // true
Number.isInteger(1.2) // false
[] instanceof Array // true
{} instanceof Object // true
new Date() instanceof Date // true
// 注意:跨 iframe/frame 時 instanceof 失效(不同全域環境)
const Type = {
isUndefined: v => v === undefined,
isNull: v => v === null,
isBoolean: v => typeof v === 'boolean',
isNumber: v => typeof v === 'number' && !Number.isNaN(v),
isBigInt: v => typeof v === 'bigint',
isString: v => typeof v === 'string',
isSymbol: v => typeof v === 'symbol',
isFunction: v => typeof v === 'function',
isArray: Array.isArray,
isDate: v => Object.prototype.toString.call(v) === '[object Date]',
isRegExp: v => Object.prototype.toString.call(v) === '[object RegExp]',
isError: v => Object.prototype.toString.call(v) === '[object Error]',
isPlainObject: v => Object.prototype.toString.call(v) === '[object Object]',
isNumeric: v => typeof v === 'number' && isFinite(v),
getType: v => Object.prototype.toString.call(v).slice(8, -1).toLowerCase()
};
// 用法
Type.getType(null); // "null"
Type.isArray([1,2]); // true
Type.isPlainObject({}); // true
typeof 足夠。null、Array、Date 等具體引用類型,使用 Object.prototype.toString.call() 或專用 API。精準的類型判斷是健壯代碼的基石,選對工具事半功倍。