首先要說的,typeof 并不是一個方法,所以沒必要寫成 typeof() 的形式。
typeof 是一個操作符,typeof 操作符返回一個字符串,指示未經(jīng)計算的操作數(shù)的類型。
接下來我要問的是,你知道typeof 可能的返回值有哪些?
例子
常規(guī)用法
// 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
// 區(qū)分數(shù)組,普通對象
typeof [1, 2, 4] === 'object';
typeof new Date() === 'object';
// 下面的容易令人迷惑,不要使用!
typeof new Boolean(true) === 'object';
typeof new Number(1) ==== 'object';
typeof new String("abc") === 'object';
// 函數(shù)
typeof function(){} === 'function';
typeof Math.sin === 'function';
null
// 從一開始出現(xiàn)JavaScript就是這樣的
typeof null === 'object';
哈哈,我們都知道 typeof null 返回 'object',但是為什么呢?原來,在 JavaScript 最初的實現(xiàn)中,JavaScript 中的值是由一個表示類型的標簽和實際數(shù)據(jù)值表示的。對象的類型標簽是0。由于 null 代表的是空指針(大多數(shù)平臺下值為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 宿主對象是對象而不是函數(shù)
//在 IE 6, 7 和 8 中,大多數(shù)的宿主對象是對象,而不是函數(shù)
typeof alert === 'object'
總結(jié) 如下表 (from MDN)
| 類型 | 結(jié)果 |
|---|---|
| Undefined | "undefined" |
| Null | "object" |
| Boolean | "boolean" |
| Number | "number" |
| String | "string" |
| Symbol(ECMAScript 6 新增) | "symbol" |
| 宿主對象(由JS環(huán)境提供) | Implementation-dependent |
| 函數(shù)對象 | "function" |
| 任何其他對象 | "object" |