你真的懂 typeof 吗?

首先要说的,typeof 并不是一个方法,所以没必要写成 typeof() 的形式。
typeof 是一个操作符,typeof 操作符返回一个字符串,指示未经计算的操作数的类型。

接下来我要问的是,你知道 typeof 可能的返回值有哪些?

例子

常规用法
// Numbers
typeof 37 === 'number';
typeof 3.14 === 'number';
typeof Math.LN2 === 'number';
typeof Infinity === 'number';
typeof NaN === 'number'; // 尽管NaN是"Not-A-Number"的缩写
typeof Number(1) === 'number'; // 但不要使用这种形式!

// Strings
typeof "" === 'string';
typeof "bla" === 'string';
typeof (typeof 1) === 'string'; // typeof总是返回一个字符串
typeof String("abc") === 'string'; // 但不要使用这种形式!

// Booleans
typeof true === 'boolean';
typeof false === 'boolean';
typeof Boolean(true) === 'boolean'; // 但不要使用这种形式!

// Symbols
typeof Symbol() === 'symbol';
typeof Symbol('foo') === 'symbol';
typeof Symbol.iterator === 'symbol';

// Undefined
typeof undefined === 'undefined';
typeof declaredButUndefinedVariable === 'undefined';
typeof undeclaredVariable === 'undefined'; 

// Objects
typeof {a:1} === 'object';

// 使用Array.isArray 或者 Object.prototype.toString.call
// 区分数组,普通对象
typeof [1, 2, 4] === 'object';

typeof new Date() === 'object';

// 下面的容易令人迷惑,不要使用!
typeof new Boolean(true) === 'object';
typeof new Number(1) ==== 'object';
typeof new String("abc") === 'object';

// 函数
typeof function(){} === 'function';
typeof Math.sin === 'function';
null
// 从一开始出现JavaScript就是这样的
typeof null === 'object';

哈哈,我们都知道 typeof null 返回 ‘object’,但是为什么呢?原来,在 JavaScript 最初的实现中,JavaScript 中的值是由一个表示类型的标签和实际数据值表示的。对象的类型标签是0。由于 null 代表的是空指针(大多数平台下值为0x00),因此,null的类型标签也成为了0,typeof null就错误的返回了’object’.

正则表达式
//对正则表达式字面量的类型判断在某些浏览器中不符合标准:
typeof /s/ === 'function'; // Chrome 1-12 , 不符合 ECMAScript 5.1
typeof /s/ === 'object'; // Firefox 5+ , 符合 ECMAScript 5.1

//我目前版本的Chrome(60.0.3112.90)
typeof /s/ === 'object';

番外:IE 宿主对象是对象而不是函数

//在 IE 6, 7 和 8 中,大多数的宿主对象是对象,而不是函数
typeof alert === 'object'

总结 如下表 ( from MDN

类型 结果
Undefined “undefined”
Null “object”
Boolean “boolean”
Number “number”
String “string”
Symbol(ECMAScript 6 新增) “symbol”
宿主对象(由JS环境提供) Implementation-dependent
函数对象 “function”
任何其他对象 “object”
over