前端開發時常需要判斷變數的型別。由於 ECMAScript 是松散型別語言,變數本身不帶型別資訊,因此語言提供了 typeof 這個運算子來回答「這是什麼型別」。
對一個值使用 typeof,會得到下列其中一個字串:
"undefined" — 值未定義"boolean" — 布林值"string" — 字串"number" — 數值"object" — 物件或 null"function" — 函式
(嚴格來說還有 "symbol"(ES6)與 "bigint"(ES2020),共八種。)
var n;
console.log(typeof n); // "undefined"
n = 1; console.log(typeof n); // "number"
n = "1"; console.log(typeof n); // "string"
n = false; console.log(typeof n); // "boolean"
n = { name: "obj" }; console.log(typeof n); // "object"
n = new Number(5); console.log(typeof n); // "object" ← 注意
n = function () { return; }; console.log(typeof n); // "function"
typeof 的操作數可以是變數,也可以是字面值。而且要記住它是運算子而非函式,所以 typeof(x) 那對括號只是普通的群組運算子,並非函式呼叫參數——兩種寫法效果相同。
從上面的例子可以看到,new Number(66) 的 typeof 是 "object",因為所有用建構函式(透過 new)產生的東西都是物件。那要怎麼區分 Number、String、Array、Function、Date、Boolean、Error 這些內建物件?答案是借用 Object.prototype.toString:
var n, res;
n = new Number(66);
res = Object.prototype.toString.call(n);
console.log(res); // "[object Number]"
n = new String("string");
res = Object.prototype.toString.call(n);
console.log(res); // "[object String]"
n = [];
res = Object.prototype.toString.call(n);
console.log(res); // "[object Array]"
n = new Date();
console.log(Object.prototype.toString.call(n)); // "[object Date]"
n = null;
console.log(Object.prototype.toString.call(n)); // "[object Null]"
這招之所以可靠,是因為每個物件內部都有一個未被污染的 [[Class]] 標記。但要特別用 Object.prototype.toString.call() 而不是 n.toString()——因為某些物件會覆寫自己的 toString,導致結果失真。
這是 JavaScript 從 1995 年流傳至今的 bug。null 理應是「空值」,卻被判為物件。想準確判斷 null,只能寫 value === null。
console.log(typeof undeclaredVar); // "undefined",不拋錯
console.log(undeclaredVar); // ReferenceError
這個特性可以用來安全地做特性偵測,但也容易讓拼字錯誤被靜靜吞掉。
// 數字(排除 NaN)
typeof x === 'number' && !isNaN(x)
// 字串
typeof x === 'string'
// 布林
typeof x === 'boolean'
// 函式
typeof x === 'function'
// 陣列:不要用 typeof,它會回 "object"
Array.isArray(x)
// 純物件
Object.prototype.toString.call(x) === '[object Object]'
// null
x === null
// 兩者皆可(null 與 undefined)
x == null
最後一條 x == null 用了不嚴格相等,是少數「== 優於 ===」的合理場合,因為同時命中 null 與 undefined 正好符合「沒有值」的語意。若團隊偏好明確,也可以寫 x === null || x === undefined,ES2020 之後還有 x ?? defaultValue 這個空值合併運算子可用。