讓初學(xué)者又愛(ài)又恨的typeof運(yùn)算符

初學(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ì)更好;

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容