0

Possible Duplicate:
What makes a jQuery object show up as an array in Chrome's Developer Tools?

I would like to know why this behavior in javascript console:

In this example everything is clear:

var obj = {find: function () {}}
obj // Object { find=function()}
obj.find // function()

In the following example I would like some explanation about the output of $.fn

I would expect the output of $.fn like an Object containing keys and values, but ....

$.fn // [] // ***************** freaky part ****************
$.fn.find // function()
Community
  • 1
  • 1
antonjs
  • 14,060
  • 14
  • 65
  • 91

2 Answers2

3

$.fn has both length and splice properties, which fools the console into thinking it's an array.

> $.fn
[]
> delete $.fn.length   // or delete $.fn.splice
true
> $.fn
  Object
Alnitak
  • 334,560
  • 70
  • 407
  • 495
  • It also happens when `delete $.fn.splice`; both are necessary to trick the console. – pimvdb Mar 16 '12 at 14:22
  • @pimvdb yes, I see that from the answer to the other question, although I wasn't aware of that when I answered this one. – Alnitak Mar 16 '12 at 14:23
  • Oh, I didn't realize it was the array part that was freaky. – Erik Reppen Mar 16 '12 at 14:23
  • @ErikReppen you should delete your answer before someone down votes it for being irrelevant... – Alnitak Mar 16 '12 at 14:29
  • @Alnitak your explanation is clear but if I run the following var obj = {length:2, splice: function(){}} the result is a little different [undefined, undefined]. Why? – antonjs Mar 16 '12 at 14:34
  • 1
    @AntonJs: You gave it a `length` of 2. –  Mar 16 '12 at 14:38
  • @am not i am var obj = {length:2, splice: function(){}, bar: 1, foo: 2} now is an object with length 4 but the output is [undefined, undefined] (in firebug console) – antonjs Mar 16 '12 at 14:45
  • @AntonJs: Objects don't have length. It's relying on the accuracy of your `.length` property. Anyway, you should keep in mind that how a console displays any information is entirely up to the console, and the criteria it uses to decide what something is can change. So all that to say that there are no rules for consoles to follow. Their behaviors can change tomorrow if they choose. The console display isn't part of the language specification, and it doesn't have any direct access to the JavaScript interpreter. That's why it has to play this guessing game with `.length` and `.splice` –  Mar 16 '12 at 14:48
  • @AntonJs: If you expect to get `[1, 2]` - you'll need to use keys that array use, which are numeric indices: `{length:2, splice: function(){}, 0: 1, 1: 2}`. – pimvdb Mar 16 '12 at 15:44
-2
$('body').find('div') //<-- that's a prototyped method of the object that $ returns
Adi
  • 5,089
  • 6
  • 33
  • 47
Erik Reppen
  • 4,605
  • 1
  • 22
  • 26