jQuery1.6 類型判斷實現代碼

來源:互聯網
上載者:User

首先定義了
全域變數class2type = {};
rdigit = /\d/,//正則判斷是否是數字
toString = Object.prototype.toString;
通過jQuery.each,定義class2type的屬性和值:
複製代碼 代碼如下:
  jQuery.each("Boolean Number String Function Array Date RegExp Object".split(" "), function(i, name) {
class2type[ "[object " + name + "]" ] = name.toLowerCase();
});
  type: function( obj ) {
return obj == null ?String( obj ) :class2type[ toString.call(obj) ] || "object";//js 裡一切都是對象,所以可以用toString.call(obj)返回對應物件類型
      //如果直接使用這個方法來判斷類型的話,IE下document.getElementById認為是object,其他瀏覽器則認為是function
      //如果傳入的值是NaN的話,會返回"number"
  }
  isFunction: function( obj ) {return jQuery.type(obj) === "function";}//在IE下,如果傳入document.getElementById,返回的是false,IE為它是object
  isArray: Array.isArray || function( obj ) {return jQuery.type(obj) === "array";}//如果原生Array擁有isArray方法則使用Array.isArray,否則自訂這個方法
  isWindow: function( obj ) {return obj && typeof obj === "object" && "setInterval" in obj;}//判斷是否為window對象
  isNaN: function( obj ) {return obj == null || !rdigit.test( obj ) || isNaN( obj );}//
  isEmptyObject: function( obj ) {
for ( var name in obj ) {//判斷的依據是看對象是否有屬性或者方法
return false;
}
return true;
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.