Note that there are some explanatory texts on larger screens.

plurals
  1. POArray Like Objects in Javascript
    primarykey
    data
    text
    <p>I'm wondering how jQuery constructs its array-like object. The key thing I'm trying to work out is how it manages to get the console to interpret it as an array and display it as such. I know it has something to do with the length property, but after playing a bit I can't quite figure it out. </p> <p>I know this has no technical advantage over a normal array like object as in the example below. But I think it's an important semantic element when users are testing and debugging.</p> <p>A normal Array like Object.</p> <pre><code>function foo(){ // Array like objects have a length property and it's properties use integer // based sequential key names, e.g. 0,1,2,3,4,5,6 just like an array. this.length = 1; this[0] = 'hello' } // Just to make sure add the length property to the prototype to match the Array // prototype foo.prototype.length = 0; // Give the Array like object an Array method to test that it works foo.prototype.push = Array.prototype.push // Create an Array like object var bar = new foo; //test it bar.push('world'); console.log(bar); // outputs { 0: 'hello', 1: 'world', length: 2, __proto__: foo } </code></pre> <p>Where as jQuery would output</p> <pre><code>var jQArray = $('div') console.log(jQArray); // outputs [&lt;div&gt;&lt;/div&gt;,&lt;div&gt;&lt;/div&gt;,&lt;div&gt;&lt;/div&gt;,&lt;div&gt;&lt;/div&gt;] </code></pre> <p>If you run </p> <pre><code>console.dir(jQArray) // Outputs { 0: HTMLDivElement, 1: HTMLDivElement, 2: HTMLDivElement, 3: HTMLDivElement, 4: HTMLDivElement, context: HTMLDocument, length: 5, __proto__: Object[0] } </code></pre> <p>The proto of the jQuery object is especially interesting since its the Object and not jQuery.fn.init as would be expected, also the [0] indicates something as this is what you get when you. </p> <pre><code>console.dir([]) // outputs Array[0] as the object name or Array[x] x being the internal length of the // Array </code></pre> <p>I have no idea how jQuery has set it's proto to be Object[0] but my guess is that answer lies somewhere in there. Anyone got any ideas?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload