typeof
操作符傳回一個字元串
typeof
typeof
可能的傳回值
類型 | 結果 |
---|---|
Undefined | undefined |
Null | object |
Boolean | boolean |
Number | number |
BigInt | bigint |
String | string |
Symbol | symbol |
Function | function |
其他任何對象 | object |
number
// 數值
typeof(42) === 'number';
typeof Math.LN2 === 'number';
typeof Infinity === 'number';
typeof NaN === 'number'; // 盡管它是 "Not-A-Number" (非數值) 的縮寫
typeof Number(1) === 'number'; // Number 會嘗試把參數解析成數值
bigint
typeof 42n === 'bigint';
string
// 字元串
typeof '' === 'string';
typeof `template literal` === 'string';
typeof '1' === 'string'; // 注意内容為數字的字元串仍是字元串
typeof (typeof 1) === 'string'; // typeof 總是傳回一個字元串
typeof String(1) === 'string'; // String 将任意值轉換為字元串,比 toString 更安全
bollean
// 布爾值
typeof true === 'boolean';
typeof false === 'boolean';
typeof Boolean(1) === 'boolean'; // Boolean() 會基于參數是真值還是虛值進行轉換
typeof !!(1) === 'boolean'; // 兩次調用 ! (邏輯非) 操作符相當于 Boolean()
symbol
// Symbols
typeof Symbol() === 'symbol';
typeof Symbol('foo') === 'symbol';
typeof Symbol.iterator === 'symbol';
undefined
// Undefined
typeof undefined === 'undefined';
typeof undeclaredVariable === 'undefined';
object
typeof {a: 1} === 'object';
typeof [1, 2, 4] === 'object';
typeof new Date() === 'object';
typeof /regex/ === 'object';
typeof new Boolean(true) === 'object';
typeof new Number(1) === 'object';
typeof new String('abc') === 'object';
function
typeof function() {} === 'function';
typeof class C {} === 'function'
typeof Math.sin === 'function';
typeof console.log // 'function'
null:雖然 typeof null 會輸出 object,但是這隻是 JS 存在的一個悠久 Bug。在 JS 的最初版本中使用的是 32 位系統,為了性能考慮使用低位存儲變量的類型資訊,000 開頭代表是對象然而 null 表示為全零,是以将它錯誤的判斷為 object 。
typeof null === 'object';
除 Function 外的所有構造函數的類型都是 'object'
var str = new String('String');
var num = new Number(100);
typeof str; // 傳回 'object'
typeof num; // 傳回 'object'
var func = new Function();
typeof func; // 傳回 'function'
文法中的括号
// 括号有無将決定表達式的類型。
var iData = 99;
typeof iData + ' Wisen'; // 'number Wisen'
typeof (iData + ' Wisen'); // 'string'
es6之前
typeof
總能保證對任何所給的操作數傳回一個字元串。即便是沒有聲明的辨別符,
typeof
也能傳回
'undefined'
。
es6加入了塊級作用域的 let 和 const 之後,在其被聲明之前對塊中的 let 和 const 變量使用 typeof 會抛出一個 ReferenceError。
typeof newConstVariable; // ReferenceError
const newConstVariable = 'hello';