Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does jQuery make the returned value look like an array?

Tags:

jquery

jQuery(); //[]
jQuery("#footer"); //[<div id="footer">...</div>]

I know that you can do something like this:

function kablam(tag) {
    var els = document.getElementsByTagName(tag);
    els.isKablam = true;
    return els;
}
var body = kablam("body"); //[<body class="ask-page">...</body>]
body.isKablam; //true

To return an "extended" version of the NodeList that's returned from document.getElementsByTagName.

However, jQuery does the opposite. It merges the result into itself (as can be seen here and here). Furthermore, that doesn't explain how it returns an array-like-object-that-looks-like-an-array when you pass nothing to it:

jQuery(); //[]

When you do that, jQuery simply returns itself. (source)

Or to the same extend, when you select the body tag:

jQuery("body"); //[<body class="ask-page">...</body>]

(source)

Or, come to think of it, anything at all:

var o = {}, body = document.getElementsByTagName("body");
jQuery.merge(o, body); //Object, not [...]

Returning array-like objects is super easy, since assigning numeric keys is trivial and no different than assigning any other key. But how does jQuery make it "look like" an array?

like image 994
Zirak Avatar asked Oct 21 '11 07:10

Zirak


1 Answers

You need to define .length, .splice and .push on a prototype for it display like an array.

Some other combination of array methods may also work.

Example

like image 58
Raynos Avatar answered Sep 22 '22 17:09

Raynos