Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
272 views
in Technique[技术] by (71.8m points)

javascript - What makes Firebug/Chrome console treat a custom object as an array?

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:

Chrome's console shows a jQuery selection as an array

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);
}

Chrome's console shows the object as a normal object

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;
}

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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;

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 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...