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.all 与 typeof 运算符的异常行为来自其以前用于检测旧版浏览器的用法。有关更多信息,请参阅为什么 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;