10

I'm wondering how it's possible that jQuery objects show up as an array in the console log of Developer Tools in Chrome.

E.g. if I execute $('<a>'), what I see in the console log is:

[<a>​</a>​]

But the following statements are false:

var a = $("<a>");

Array.isArray(a);   // false
a instanceof Array; // false

I tried to modify jQuery and see what happens, and one thing that was surprising is that removing length from the jQuery function removes the array notation:

length: 0, // commenting this line removes array notation

Instead, it then shows up as (arrow is that solid one to expand):

> jQuery.jQuery.fn.jQuery.init

But, if I try to make my own constructor which is supposed to be displayed in array notation, it does not work:

var test = function() { this.length = 0 };

new test();

// Logged (arrow is same one as before):
// > test

So I'm wondering what in the jQuery code makes Developer Tools show instances as an array. What property/function/thing is added to jQuery that makes Developer Tools handle it as an array when displaying an instance?

OrangeDog
  • 36,653
  • 12
  • 122
  • 207
pimvdb
  • 151,816
  • 78
  • 307
  • 352

2 Answers2

11

From http://api.jquery.com/jQuery.makeArray/:

Many methods, both in jQuery and in JavaScript in general, return objects that are array-like. For example, the jQuery factory function $() returns a jQuery object that has many of the properties of an array (a length, the [] array access operator, etc.), but is not exactly the same as an array and lacks some of an array's built-in methods (such as .pop() and .reverse()).

Basically, The object has to have length and splice properties to be array-like. Here is a relevant SO question: Array Like Objects in Javascript

Community
  • 1
  • 1
Boris Smus
  • 8,220
  • 2
  • 36
  • 33
  • 5
    To prove it you can run `console.log({'0': 'asd','1': 'asd', length: 2, splice: function () {}})` in the console. – Quentin Feb 23 '12 at 10:20
  • anyone knows why does Chrome treats `splice` differently? fyi this only works in Chrome but not other browser. – yqlim Nov 15 '17 at 09:53
4

You probably know this, but console.log is not displaying passed content "as is", it is trying to be "smart" and does some post processing. If you want to see original object "as is", there is console.dir method.

serg
  • 109,619
  • 77
  • 317
  • 330
  • 2
    I know about `console` capabilities; I was just wondering how jQuery made itself show up as an array while it isn't one. – pimvdb Aug 31 '11 at 18:56