In JavaScript, there are objects that pretend to be arrays (or are "array-like"). Such objects are arguments
, NodeList
s (returned from getElementsByClassName
, etc.), and jQuery objects.
When console.log
ged, 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.log
ged, 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.
arguments
worked. I wanted to know why they are logged as arrays. :-P – Rocket Hazmat Aug 9 '12 at 15:38arguments
works. It's how various consoles work, which may be different from each other. Perhaps I misinterpreted your sentence above a bit. – squint Aug 9 '12 at 15:39