初學(xué)者對(duì)于數(shù)據(jù)類型傻傻分不清楚;對(duì)typeof這個(gè)運(yùn)算符又愛(ài)又恨;下面就說(shuō)說(shuō)typeof這個(gè)運(yùn)算符:
語(yǔ)法
typeof運(yùn)算符后跟操作數(shù):
| 類型 | 結(jié)果 |
| Undefined | "undefined" |
| Null | "object"|
| Boolean | "boolean"|
| Number | "number" |
| String | "string" |
| Symbol (ECMAScript 6 新增) | "symbol" |
| 函數(shù)對(duì)象 | "function" |
| 任何其他對(duì)象 | "object" |
示例
//Number
typeof 37 === 'number';
typeof 3.14 === 'number';
typeof Math.LN2 === 'number';
typeof Infinity === 'number';
typeof NaN === 'number'; // 盡管NaN是"Not-A-Number"的縮寫(xiě)
typeof Number(1) === 'number'; // 但不要使用這種形式!
// Strings
typeof "" === 'string';
typeof "bla" === 'string';
typeof (typeof 1) === 'string'; // typeof總是返回一個(gè)字符串
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ū)分?jǐn)?shù)組,普通對(duì)象
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 class C{} === 'function'
typeof Math.sin === 'function';
typeof new Function() === 'function';</pre>
null
typeof null === 'object'; // 從一開(kāi)始出現(xiàn)JavaScript就是這樣的
大家可以收藏這篇文章;隨時(shí)拿出來(lái)看看,慢慢的就記住了;其實(shí)也不是死記硬背;理解著記憶會(huì)更好;