tylertrotter
tylertrotter

Reputation: 372

Is there such a thing as an array/object hybrid?

I'm using an npm module called horseman which is basically PhantomJS for Node. When I console log the contents of a horseman object it has all sorts of data about the current page. Included in all this data is a list of all the resources of a page and their http status codes like this:

responses: [ 'http://tylertrotter.com/': 301,
  'http://www.tylertrotter.com/': 200,
  'http://www.tylertrotter.com/css/main.css': 200, 
  ...
]

It looks like an array/object hybrid and I've never encountered something like this before. Array.isArray(responses) yields true but responses.length turns up with 0.

What is this thing?

Full console log of entire horseman object here: https://gist.github.com/tylertrotter/be8da3e777c16a2b631d9de9fc94f70b

Upvotes: 2

Views: 351

Answers (1)

Bergi
Bergi

Reputation: 665122

Is there such a thing? No, every array is this thing.

Arrays are just a special type of object in JS (like RegExp or Date instances), and they can have arbitrary properties assigned to them. Of course, a for loop will only consider its .length and iterate integer indices, but that doesn't prevent the object from containing anything. console.log typically does show such arrays in the style you have spotted.

It should be noted however that abusing arrays like this is considered a very bad practise. You should file a bug with the module and tell them to use objects are even better Maps as collections.

Upvotes: 2

Related Questions