【范圍】typeof返回值范圍:
類型 | 結果 |
String | "string" |
Number | "number" |
Boolean | "boolean" |
Undefined | "undefined" |
Object | "object" |
function函數對象 | "function" |
Symbol(ES6新增) | "symbol" |
宿主對象(由JS環境提供) | Implementation-dependent |
【typeof為什么要區分object和function?】
- 答案一:《JavaScript高級程序設計》:從技術角度講,函數在ECMAScript中是對象,不是一種數據類型。然而,函數也確實有一些特殊的屬性,因此通過typeof操作符來區分函數和其他對象是有必要的。
- 答案二:在實際的使用過程中有必要區分Object和Function,所以在typeof這里實現了
【typeof的不足之處】
- 不能區分對象、數組、正則,對它們操作都返回"object";(正則特殊一點后面說)
- Safar5,Chrome7之前的版本對正則對象返回 'function'
- 在IE6,7和8中,大多數的宿主對象是對象,而不是函數;如:typeof alert; //object
- 而在非ID瀏覽器或則IE9以上(包含IE9),typeof alert; //function
【記憶行為】
- 根據JS數據類型記憶String/Number/Boolean/Undefined/Object/function返回的字符串形式分別為:string/number/boolean/undefined/object/function
- 特殊記憶:
- Symbol(ES6新增)=> "symbol"
- 不能區分對象、數組、正則,返回"object",正則在Safar5,Chrome7之前的版本中返回"function"
- 宿主對象,IE6/7/8返回"object",其他瀏覽器返回"function"
- 特殊中的特殊
typeof 1/0; //NaN(這個NaN不是字符串類型,是數值類型) typeof typeof 1/0; //NaN(這個NaN不是字符串類型,是數值類型) typeof(1/0); //"number" typeof typeof(1/0); //"string" typeof(typeof 1/0); //"number"
【題目和答案】
// 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'; //NaN typeof 1/0 === 'NaN';