jQuery对象为何可像数组般通过索引访问DOM元素?
Great question! Let's unpack exactly why this works—it's a clever design choice that makes jQuery feel intuitive to use.
First, let's clarify what $('selector') returns: it's not a native JavaScript array (which is why Array.isArray(divTest) returns false), but an array-like object that wraps your matched DOM elements. Array-like objects have numeric indexes and a length property just like arrays, but they don't inherit from Array.prototype (so they don't come with native array methods like map() or filter() out of the box).
Now, let's connect this to jQuery.makeArray and the init method you noticed. When you run $('.test'), here's roughly what happens under the hood:
- The
initmethod first finds all DOM elements matching the.testselector, resulting in a nativeNodeList(which is itself array-like). - It calls
jQuery.makeArray(selector, this)—here,thisrefers to the new jQuery instance being created. makeArraydoes two critical things to shape the jQuery object:- It iterates over the matched DOM elements and assigns each one to the jQuery instance using numeric indexes (so
instance[0]gets the first element,instance[1]the second, and so on). - It sets the
lengthproperty of the jQuery instance to the number of matched elements, completing the array-like structure.
- It iterates over the matched DOM elements and assigns each one to the jQuery instance using numeric indexes (so
To visualize, your divTest object looks something like this:
{ 0: <div class="test first"></div>, 1: <div class="test second"></div>, 2: <div class="test third"></div>, length: 3, // Plus all jQuery prototype methods like .css(), .click(), .each(), etc. }
Since JavaScript lets you access object properties via bracket notation (object[key]), using divTest[0] directly grabs the DOM element stored at the 0 key of the jQuery object.
One quick side note: if you ever need a true array of the DOM elements, jQuery provides the .toArray() method:
var divArray = $('.test').toArray(); Array.isArray(divArray); // true
So to wrap it up: jQuery uses makeArray to convert a collection of DOM elements into an array-like object, giving it numeric indexes and a length property. That's why you can access elements like you would with a regular array, even though it's technically a custom jQuery object.
内容的提问来源于stack exchange,提问作者Younghun Jung

