...] I know you can do som...">

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

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

I know 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 the "extended" version of NodeList that came back from document.getElementsByTagName .

However, jQuery does the opposite. It combines the result into itself (as can be seen here and here ). Also, this does not explain how it returns an array similar to an object that looks like an array when you don't pass anything to it:

 jQuery(); //[] 

When you do this, jQuery just returns itself. ( source )

Or to the same extent when you select the body tag:

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

( source )

Or, think about it, anything:

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

Returned objects, like an array, are very simple, because the assignment of the numeric keys is trivial and does not differ from the assignment of another key. But how does jQuery make it look like an array?

+8
jquery
source share
2 answers

You need to define .length , .splice and .push in the prototype so that it appears as an array.

Another combination of array methods may also work.

Example

+7
source share

What do you think looks like an array? How would you check for massiveness? If you consider everything that has length to be an array, then all you need to make the object look like an array is to define the length property. jQuery do it.

0
source share

All Articles