typeof
typeof 運算子返回一個字串,指示運算元值的型別。
試一試
console.log(typeof 42);
// Expected output: "number"
console.log(typeof "blubber");
// Expected output: "string"
console.log(typeof true);
// Expected output: "boolean"
console.log(typeof undeclaredVariable);
// Expected output: "undefined"
語法
typeof operand
引數
描述
下表總結了 typeof 可能的返回值。有關型別和原始值的更多資訊,另請參閱 JavaScript 資料結構頁面。
| 型別 | 結果 |
|---|---|
| Undefined | "undefined" |
| Null | "object"(原因) |
| Boolean | "boolean" |
| Number | "number" |
| BigInt | "bigint" |
| String | "string" |
| 符號 | "symbol" |
| 函式(在 ECMA-262 術語中實現 [[Call]];類也是函式) | "function" |
| 任何其他物件 | "object" |
此值列表是詳盡的。沒有報告符合規範的引擎會產生(或歷史上曾產生過)列出之外的值。
示例
基本用法
// Numbers
typeof 37 === "number";
typeof 3.14 === "number";
typeof 42 === "number";
typeof Math.LN2 === "number";
typeof Infinity === "number";
typeof NaN === "number"; // Despite being "Not-A-Number"
typeof Number("1") === "number"; // Number tries to parse things into numbers
typeof Number("shoe") === "number"; // including values that cannot be type coerced to a number
typeof 42n === "bigint";
// Strings
typeof "" === "string";
typeof "bla" === "string";
typeof `template literal` === "string";
typeof "1" === "string"; // note that a number within a string is still typeof string
typeof typeof 1 === "string"; // typeof always returns a string
typeof String(1) === "string"; // String converts anything into a string, safer than toString
// Booleans
typeof true === "boolean";
typeof false === "boolean";
typeof Boolean(1) === "boolean"; // Boolean() will convert values based on if they're truthy or falsy
typeof !!1 === "boolean"; // two calls of the ! (logical NOT) operator are equivalent to Boolean()
// Symbols
typeof Symbol() === "symbol";
typeof Symbol("foo") === "symbol";
typeof Symbol.iterator === "symbol";
// Undefined
typeof undefined === "undefined";
typeof declaredButUndefinedVariable === "undefined";
typeof undeclaredVariable === "undefined";
// Objects
typeof { a: 1 } === "object";
// use Array.isArray or Object.prototype.toString.call
// to differentiate regular objects from arrays
typeof [1, 2, 4] === "object";
typeof new Date() === "object";
typeof /regex/ === "object";
// The following are confusing, dangerous, and wasteful. Avoid them.
typeof new Boolean(true) === "object";
typeof new Number(1) === "object";
typeof new String("abc") === "object";
// Functions
typeof function () {} === "function";
typeof class C {} === "function";
typeof Math.sin === "function";
typeof null
// This stands since the beginning of JavaScript
typeof null === "object";
在 JavaScript 的第一次實現中,JavaScript 值由型別標籤和值表示。物件的型別標籤是 0。null 被表示為 NULL 指標(在大多數平臺上是 0x00)。因此,null 的型別標籤是 0,從而導致 typeof 返回值 "object"。(參考)
ECMAScript 曾提出過一個修復方案(透過選擇性加入),但被拒絕了。它會導致 typeof null === "null"。
使用 new 運算子
所有使用 new 呼叫的建構函式都將返回非原始值("object" 或 "function")。大多數返回物件,但一個顯著的例外是 Function,它返回一個函式。
const str = new String("String");
const num = new Number(100);
typeof str; // "object"
typeof num; // "object"
const func = new Function();
typeof func; // "function"
語法中需要括號
typeof 運算子的優先順序高於加法(+)等二元運算子。因此,需要括號來評估加法結果的型別。
// Parentheses can be used for determining the data type of expressions.
const someData = 99;
typeof someData + " foo"; // "number foo"
typeof (someData + " foo"); // "string"
與未宣告和未初始化變數的互動
typeof 通常始終保證為它提供的任何運算元返回一個字串。即使對於未宣告的識別符號,typeof 也會返回 "undefined" 而不是丟擲錯誤。
typeof undeclaredVariable; // "undefined"
但是,在同一塊中,在宣告位置之前對詞法宣告(let、const 和 class)使用 typeof 將丟擲 ReferenceError。塊作用域變數從塊的開始到初始化處理完成之前都處於暫時性死區,在此期間如果被訪問將丟擲錯誤。
typeof newLetVariable; // ReferenceError
typeof newConstVariable; // ReferenceError
typeof newClass; // ReferenceError
let newLetVariable;
const newConstVariable = "hello";
class newClass {}
document.all 的異常行為
所有當前瀏覽器都暴露了一個非標準的宿主物件 document.all,其型別為 undefined。
typeof document.all === "undefined";
儘管 document.all 也是虛值並寬鬆等於 undefined,但它不是 undefined。document.all 型別為 "undefined" 的情況在 Web 標準中被歸類為對原始 ECMAScript 標準的“蓄意違反”,以實現 Web 相容性。
獲取更具體型別的自定義方法
typeof 非常有用,但它不像可能需要的那樣通用。例如,typeof [] 是 "object",typeof new Date()、typeof /abc/ 等也是。
為了在檢查型別時獲得更大的特異性,我們在此介紹一個自定義的 type(value) 函式,它在很大程度上模仿了 typeof 的行為,但對於非原始值(即物件和函式),它儘可能返回更細粒度的型別名稱。
function type(value) {
if (value === null) {
return "null";
}
const baseType = typeof value;
// Primitive types
if (!["object", "function"].includes(baseType)) {
return baseType;
}
// Symbol.toStringTag often specifies the "display name" of the
// object's class. It's used in Object.prototype.toString().
const tag = value[Symbol.toStringTag];
if (typeof tag === "string") {
return tag;
}
// If it's a function whose source code starts with the "class" keyword
if (
baseType === "function" &&
Function.prototype.toString.call(value).startsWith("class")
) {
return "class";
}
// The name of the constructor; for example `Array`, `GeneratorFunction`,
// `Number`, `String`, `Boolean` or `MyCustomClass`
const className = value.constructor.name;
if (typeof className === "string" && className !== "") {
return className;
}
// At this point there's no robust way to get the type of value,
// so we use the base implementation.
return baseType;
}
為了檢查可能不存在的變數(否則會丟擲 ReferenceError),請使用 typeof nonExistentVar === "undefined",因為這種行為無法透過自定義程式碼模仿。
規範
| 規範 |
|---|
| ECMAScript® 2026 語言規範 # sec-typeof-operator |
瀏覽器相容性
載入中…