JavaScript typeof操作符
12 Jun 2014Javascript是一门弱类型语言,它拥有动态类型的特性,也就是说同一个变量可以作为不同的类型被应用到代码中.
typeof操作符作为一个全局的function, 可以被用作查询变量的类型.
// Numbers
typeof 37 === 'number';
typeof 3.14 === 'number';
typeof Math.LN2 === 'number';
typeof Infinity === 'number';
typeof NaN === 'number'; // Despite being "Not-A-Number"
typeof Number(1) === 'number'; // but never use this form!
// Strings
typeof "" === 'string';
typeof "bla" === 'string';
typeof (typeof 1) === 'string'; // typeof always return a string
typeof String("abc") === 'string'; // but never use this form!
// Booleans
typeof true === 'boolean';
typeof false === 'boolean';
typeof Boolean(true) === 'boolean'; // but never use this form!
// Undefined
typeof undefined === 'undefined';
typeof blabla === 'undefined'; // an undefined variable
// Objects
typeof {a:1} === 'object';
// use Array.isArray or Object.prototype.toString.call
// to differentiate regular objects from arrays
typeof [1, 2, 4] === 'object';
typeof new Date() === 'object';
// The following is confusing. Don't use!
typeof new Boolean(true) === 'object';
typeof new Number(1) === 'object';
typeof new String("abc") === 'object';
// Functions
typeof function(){} === 'function';
typeof Math.sin === 'function';
typeof 返回值与类型的对应关系如下表:
Type | Return Value |
---|---|
Undefined | "undefined" |
Null | "object" |
Boolean | "boolean" |
Number | "number" |
String | "string" |
Host object(provided by the JS environment) | Implementation-dependent |
Function object (implements [[Call]] in ECMA-262 terms) | "function" |
Any other object | "object" |
对于上表中的Host Object, 借用stackoverflow中的解释:
###native object object in an ECMAScript implementation whose semantics are fully defined by this specification rather than by the host environment. NOTE Standard native objects are defined in this specification. Some native objects are built-in; others may be constructed during the course of execution of an ECMAScript program.
###host object object supplied by the host environment to complete the execution environment of ECMAScript. NOTE Any object that is not native is a host object.
###A few examples: Native objects: Object (constructor), Date, Math, parseInt, eval, string methods like indexOf and replace, array methods, … Host objects (assuming browser environment): window, document, location, history, XMLHttpRequest, setTimeout, getElementsByTagName, querySelectorAll, …
注意
- null的typeof返回值为”object”
- 对于IE浏览器, Host Object返回值为”object”而不是”function”
- 正则表达式的type,因浏览器是否符合ECMA标准而异
typeof /s/ === 'function'; // Chrome 1-12 Non-conform to ECMAScript 5.1 typeof /s/ === 'object'; // Firefox 5+ Conform to ECMAScript 5.1