In JavaScript, there are objects that pretend to be arrays (or are “array-like”). Such objects are arguments, NodeLists (returned from getElementsByClassName, etc.), and jQuery objects.
When console.logged, they appear as arrays, but they are not. I know that in order to be array-like, an object must have a length property.
So I made an “object” like this:
function foo(){
this.length = 1;
this[0] = "bar";
}
var test = new foo;
When I console log(test), I get (as expected) a foo object. I can “convert” it to an array using
Array.prototype.slice.call(test)
But, I don’t want to convert it, I want it to be array-like. How do I make an array-like object, so that when it’s console.logged, it appears as an array?
I tried setting foo.prototype = Array.prototype, but console.log(new foo) still shows a foo object, and not an array.
Depends specifically on the console. For custom objects in Chrome’s developer console, and Firebug you’ll need both the
lengthandspliceproperties.splicewill also have to be a function.It’s important to note, however, that there is no official standard.
The following code is used by jQuery (v1.11.1) internally to determine if an object should use a
forloop or afor..inloop:Note that it’s possible to have an object that appears in the console as an array (
[]) but that gets iterated over with afor..inloop in jQuery, or an object that appears as an object in the console ({}) but that gets iterated over with aforloop in jQuery.