typeof 運算子回傳一個表示運算式型別的字串。可能的值有:"number"、"string"、"boolean"、"object"、"function"、"undefined"。注意全部小寫開頭。
typeof undefined // 'undefined'
typeof null // 'object' ← 歷史遺留的 bug
typeof true // 'boolean'
typeof 123 // 'number'
typeof "abc" // 'string'
typeof function () {} // 'function'
typeof {} // 'object'
typeof [] // 'object' ← 陣列也是 object
typeof unknownVariable // 'undefined'(不報錯)
typeof 在兩種情況下回傳 "undefined":變數未宣告、變數值為 undefined。
typeof undeclaredVariable === "undefined" // true var declaredVariable; typeof declaredVariable // 'undefined' typeof undefined // 'undefined'
其他檢查 undefined 的方法:
var value = undefined; value === undefined; // true
但這種寫法用在「未宣告」的變數上會直接拋錯:
undeclaredVariable === undefined; // ReferenceError: undeclaredVariable is not defined
只有 typeof 能在不報錯的前提下檢查未宣告的變數,這是它無可取代的價值。
要注意的是,已經初始化過的情況都不會有這個問題,因為它們的值本來就是 undefined:
var declaredVariable;
declaredVariable === undefined; // true
(function (x) { return x === undefined; })(); // true(未傳參數的形參)
({}).foo === undefined; // true(不存在的屬性)
若想檢查某個可能未宣告的全域變數是否存在,也可以用 if (window.maybeUndeclaredVariable) {}。
這裡會碰到 typeof 最有名的怪異行為:
typeof null; // 'object'
這其實是初代 JavaScript 實作的 bug,但因為相容性因素,後續標準反而將它寫進了規範。V8 團隊曾嘗試修正為 "null",最後因破壞相容性而作罷。
解法:不要用 typeof 做這件事,直接比對:
function isDefined(x) {
return x !== null && x !== undefined;
}
常見的簡寫是 myValue || defaultValue,等價於:
(myValue !== undefined && myValue !== null) ? myValue : defaultValue
但要小心:這種寫法會把 0 與空字串也當成「無值」。ES6 的 ?? 運算子只判斷 null 與 undefined,是目前更精準的選擇。
function isObject(x) {
return (typeof x === "function" || (typeof x === "object" && x !== null));
}
寫起來有點繁瑣,因為 typeof 把函數與物件分成兩類,而且 null 也被歸到 object。
另一種判斷方式:
function isObject2(x) {
return x === Object(x);
}
為什麼不用 instanceof Object?因為 instanceof 是透過原型鏈判斷的,而無原型的物件確實存在:
var obj = Object.create(null); Object.getPrototypeOf(obj); // null typeof obj; // 'object' obj instanceof Object; // false
這種物件實際上並非罕見——Object.prototype 本身就是一個無原型物件。
typeof 仍是查看原始值型別的最佳工具,唯一要記得的就是 null 的例外:
function getPrimitiveTypeName(x) {
var typeName = typeof x;
switch (typeName) {
case "undefined":
case "boolean":
case "number":
case "string":
return typeName;
case "object":
if (x === null) { return "null"; }
default:
throw new TypeError("參數不是一個原始值: " + x);
}
}
更通用的做法是實作一個 getTypeName(),除了原始值,也能回傳物件的內部 [[Class]] 屬性——jQuery 的 $.type() 正是這種實作。
typeof function () {}; // 'function'
typeof Object.prototype.toString; // 'function'
原理上 instanceof Function 也可以,但瀏覽器有個歷史包袱:每個 iframe 與 window 都有自己的全域環境與建構函數。因此跨框架傳遞物件時,instanceof 會失效。這也正是 ES5 需要 Array.isArray() 的原因。
JavaScript 目前比較欠缺的幾個能力:
isDefined():判斷變數是否已賦值(ES6 的 ?? 大致解決了這個需求)isObject():語意清楚的物件判斷getTypeName():可跨 iframe 的型別名稱取得(Object.prototype.toString.call() 是目前標準解法)Array.isArray() 是唯一的官方特例)至於「檢查變數是否已宣告」這種需求,或許並不值得為它新增一個運算子。
一句話總結:typeof 用來區分原始型別很好用,但要記住兩個例外——null 回傳 "object"、[] 也回傳 "object"。需要精確判斷物件種類時,改用 Object.prototype.toString.call(x) 會可靠得多。