typeof 運算子

typeof 運算子將未評估的運算元的資料型別作為字串返回。

句法:

typeof operand

返回:

這些是 typeof 可能的返回值:

型別 返回值
Undefined undefined
Null object
Boolean boolean
Number number
String string
Symbol(ES6) symbol
Function 物件 function
document.all undefined
主機物件(由 JS 環境提供) 實現相關的
任何其他物件 object

document.alltypeof 運算子的異常行為來自其以前用於檢測舊版瀏覽器的用法。有關更多資訊,請參閱為什麼 document.all 已定義但 typeof document.all 返回 undefined

例子:

// returns 'number'
typeof 3.14;
typeof Infinity;
typeof NaN;               // "Not-a-Number" is a "number"

// returns 'string'
typeof "";
typeof "bla";
typeof (typeof 1);        // typeof always returns a string

// returns 'boolean'
typeof true;
typeof false;

// returns 'undefined'
typeof undefined;
typeof declaredButUndefinedVariable;
typeof undeclaredVariable;
typeof void 0;
typeof document.all       // see above

// returns 'function'
typeof function(){};
typeof class C {};
typeof Math.sin;

// returns 'object'
typeof { /*<...>*/ };
typeof null;
typeof /regex/;           // This is also considered an object
typeof [1, 2, 4];         // use Array.isArray or Object.prototype.toString.call.
typeof new Date();
typeof new RegExp();
typeof new Boolean(true); // Don't use!
typeof new Number(1);     // Don't use!
typeof new String("abc"); // Don't use!

// returns 'symbol'
typeof Symbol();
typeof Symbol.iterator;