javascript類型判斷

來源:互聯網
上載者:User

標籤:

javascript中,類型判斷是各大類庫的基礎之一。來看看是怎麼實現的。

主要有三種方法:

1,滿是坑的typeof  (認識其坑後是一個利器)

  typeof 返回6種基本類型:number, string, object, boolean, undefined, function

  其中有幾個很容易誤導的:

  (1)typeof obj === ‘object‘,你卻不能真正當對象使用

if (typeof obj === ‘object‘) {    obj.a() // 這裡報錯}

  (2)typeof NAN === ‘number‘,你卻不能使用它進行算術運算

if (typeof num === ‘number‘) {    num = num + 10 // 執行後num仍然是NaN}

  (3)Safar5,Chrome7之前的版本對正則對象返回 ‘function‘

  (4) 不能區分對象、數組、正則,對它們操作都返回‘object‘

 

2,遺憾的constructor 和 instanceof

  為什麼說遺憾,因為在跨文檔操作時候,會產生bug

// 用法function isArray(arr){    return typeof arr == "object" && arr.constructor == Array;}// 跨文檔操作時就呵呵了window.onload=function(){var iframe_arr=new window.frames[0].Array;alert(iframe_arr instanceof Array); // falsealert(iframe_arr.constructor == Array); // false}

 

3, 最後的解藥:Object.prototype.toString.

  直接把jQuery.2.0.3源碼貼上

class2type = {}
core_toString = class2type.toStringjQuery.each(
"Boolean Number String Function Array Date RegExp Object Error".split(" "), function(i, name) { class2type[ "[object " + name + "]" ] = name.toLowerCase();});type: function( obj ) { if ( obj == null ) { return String( obj ); } // Support: Safari <= 5.1 (functionish RegExp) return typeof obj === "object" || typeof obj === "function" ? class2type[ core_toString.call(obj) ] || "object" : typeof obj; }

 

總結:除了自訂類型外外,組合類別型基本用Object.prototype.toString這種方法。typeof方法可以用來判斷boolean, undefined, string類型

 

 

  

 

javascript類型判斷

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.