對jQuery.isArray方法的分析

來源:互聯網
上載者:User

標籤:style   blog   io   color   os   ar   sp   div   on   

jQuery.isArray方法應於判斷是不是數組,是的話返回true,否則返回false。調用如:jQuery.isArray([]),返回true。其實現源碼如下:

isArray: Array.isArray || function( obj ) {    return jQuery.type(obj) === "array";}

我們看到它的主要邏輯是先看瀏覽器支不支援Array.isArray方法,如果不支援則調應jQuery自己的jQuery.type方法,看其傳回值是不是"array"。

firefox、chrome、IE9及以上的瀏覽器都支援Array.isArray方法。其它瀏覽器就需要jQuery.type的幫忙了,jQuery.type的源碼如下:

type: function( obj ) {    if ( obj == null ) {        return obj + "";    }    return typeof obj === "object" || typeof obj === "function" ?        class2type[ toString.call(obj) ] || "object" :        typeof obj;}

代碼中的if好理解,如果傳入的null則返回“null”字串。

return 後面的代碼結構上看起來比較亂。我們整理如下:

return ( typeof obj === "object" || typeof obj === "function" )  ? ( class2type[ toString.call(obj) ] || "object" ) : typeof obj;

現在清楚多了,它是判斷( typeof obj === "object" || typeof obj === "function" )的值是不是真,如果是真則返回 ( class2type[ toString.call(obj) ] || "object" ),反之則返回 typeof obj。

所以當傳入的是字串,數字,undefined的時直接返回 typeof obj。當傳入的是對象、數組、函數時則直接返回 ( class2type[ toString.call(obj) ] || "object" )。現在主要看看class2type[ toString.call(obj) ]的實現:

var class2type = {};var toString = class2type.toString;jQuery.each("Boolean Number String Function Array Date RegExp Object Error".split(" "), function(i, name) {    class2type[ "[object " + name + "]" ] = name.toLowerCase();});

jQuery定義了class2type的一個對象,並將其初始化為如下的格式:

{    "[object Array]" : "array",    "[object Boolean]" : "boolean",    "[object Date]" : "date",    "[object Error]" : "error",    "[object Function]" : "function",    "[object Number]" : "number",    "[object Object]" : "object",    "[object RegExp]" : "regexp",    "[object String]" : "string"}

toString方法的傳回值正好是class2type對象的key值。所以class2type[ toString.call(obj) ]正好得到我們需要的傳回型別字串。

對jQuery.isArray方法的分析

聯繫我們

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