2011-02-09 45 views
14

當我在jQuery中開發時,我經常發現自己在Chrome/Firebug控制檯中輸入選擇器並查看他們給我的東西。他們總是很好地格式化,如果他們數組:什麼使Firebug/Chrome控制檯將自定義對象視爲數組?

Chrome's console shows a jQuery selection as an array

我試圖找出它是什麼,讓控制檯治療的對象數組。例如,下面的自定義對象不被視爲一個陣列:

function ElementWrapper(id) { 
    this[0] = document.getElementById(id); 
} 

Chrome's console shows the object as a normal object

如果我然後添加length屬性和splice方法,它神奇地工作作爲一個數組,與整數的任何屬性鍵視爲陣列的成員:

function ElementWrapper(id) { 
    this[0] = document.getElementById(id); 
    this.length = 1; 
    this.splice = Array.prototype.splice; 
} 

Chrome's console shows the object as if it was an array

所以基本上我的問題是:什麼決定了控制檯是否將對象顯示爲數組?是否有任何理由,或者它是完全武斷的「如果一個對象具有這些屬性,它必須是一個數組?」如果是這樣,那麼決定性的屬性是什麼?

回答

18

這是Firebug的isArray方法做:(從Firebug source

if (!obj) 
    return false; 
else if (isIE && !isFunction(obj) && typeof obj == "object" && isFinite(obj.length) && obj.nodeType != 8) 
    return true; 
else if (isFinite(obj.length) && isFunction(obj.splice)) 
    return true; 
else if (isFinite(obj.length) && isFunction(obj.callee)) // arguments 
    return true; 
else if (instanceOf(obj, "HTMLCollection")) 
    return true; 
else if (instanceOf(obj, "NodeList")) 
    return true; 
else 
    return false; 

當然,所有這些檢查確保對象是一個真正的JavaScript數組,但他們猜測是否合理工作一個對象是一個僞數組,它反過來給你一個方便的類似於數組的表示來進行調試。

Chrome可能會也可能不會使用這些相同的檢查,並且Firefox 4中的新Web控制檯不會識別除真數組之外的其他任何數據作爲數組。

+0

非常感謝 - 這是一個很好的答案! – lonesomeday 2011-02-09 22:46:02

相關問題