萬盛學電腦網

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

JavaScript typeof 運算符完整指南:類型判斷、陷阱與最佳實踐

typeof 是一元運算符,返回字符串表示操作數的類型。它是 JS 中最基礎的類型檢測工具,但存在著名的 typeof null === 'object' 等陷阱。本文系統整理返回值對照表、判斷邏輯、常見誤區與更精準的替代方案。

語法

typeof operand
typeof (operand) // 帶括號亦可,視為運算符而非函數

標準返回值對照表 (ES2024)

類型返回值示例
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()

關鍵陷阱

  1. null 返回 "object":語言設計初期失誤,已成標準不可修復。判斷 null 必須用 val === null。
  2. 無法區分 Array / Date / RegExp / 普通對象:均返回 "object"。
  3. 宿主對象可能返回非標準值:如 IE 某些 DOM 物件返回 "unknown",現代瀏覽器罕見。

精準類型判斷方案

方案一:Object.prototype.toString.call()(通用、ES3+)

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() / Number.isNaN() 等專用 API(ES5+)

Array.isArray([])      // true
Array.isArray({})      // false
Number.isNaN(NaN)      // true
Number.isInteger(1.2)  // false

方案三:instanceof(原型鏈檢測,僅限引用類型)

[] 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

總結建議

  • 僅需區分「基本類型 vs 函數 vs 其他對象」時,typeof 足夠。
  • 需區分 null、Array、Date 等具體引用類型,使用 Object.prototype.toString.call() 或專用 API。
  • 封裝統一工具庫,專案內統一調用,避免分散的類型判斷邏輯不一致。

精準的類型判斷是健壯代碼的基石,選對工具事半功倍。

copyright © 萬盛學電腦網 all rights reserved