問題描述
當我使用 jQuery 進行開發時,我經常發現自己在 Chrome/Firebug 控制臺中輸入選擇器并查看它們給我的信息.它們的格式總是很好,就好像它們是數組一樣:
When I am developing in jQuery, I frequently find myself typing selectors into the Chrome/Firebug console and seeing what they give me. They are always nicely formatted as if they were arrays:
我正在嘗試弄清楚是什么使控制臺將對象視為數組.例如,以下自定義對象不被視為數組:
I am trying to work out what it is that makes the console treat an object as an array. For instance, the following custom object is not treated as an array:
function ElementWrapper(id) {
this[0] = document.getElementById(id);
}
如果我隨后添加一個 length
屬性和一個 splice
方法,它會神奇地作為一個數組工作,任何帶有整數鍵的屬性都被視為數組的成員:
If I then add a length
property and a splice
method, it magically works as an array, with any properties with integer keys treated as members of the arrays:
function ElementWrapper(id) {
this[0] = document.getElementById(id);
this.length = 1;
this.splice = Array.prototype.splice;
}
所以本質上我的問題是:是什么決定了控制臺是否將對象顯示為數組?是否有任何理由,或者它是完全任意的如果一個對象具有這些屬性,它必須是一個數組?"如果有,決定性的屬性是什么?
So essentially my question is: what determines whether the console displays an object as an array? Is there any rationale to it, or is it a completely arbitrary "if an object has these properties, it must be an array?" If so, what are the decisive properties?
推薦答案
這就是 Firebug 的 isArray
方法的作用:(來自 Firebug 源碼)
This is what Firebug's isArray
method does: (from the 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 數組,但它們可以合理地猜測對象是否是偽數組,這反過來又為您提供了一種方便的類似數組的表示來進行調試.
Of course, none of these checks ensures that the object is a true JavaScript array, but they do a reasonable job of guessing whether an object is a pseudo-array, which in turn gives you a convenient array-like representation for debugging.
Chrome 可能會也可能不會使用這些相同的檢查,并且 Firefox 4 中的新 Web 控制臺不會將除真正數組之外的任何內容識別為數組.
Chrome may or may not use these same checks, and the new Web Console in Firefox 4 doesn't recognize anything other than true arrays as arrays.
這篇關于是什么讓 Firebug/Chrome 控制臺將自定義對象視為數組?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!