You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

jQuery对象为何可像数组般通过索引访问DOM元素?

Why can jQuery objects be accessed like arrays with indexes?

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:

  1. The init method first finds all DOM elements matching the .test selector, resulting in a native NodeList (which is itself array-like).
  2. It calls jQuery.makeArray(selector, this)—here, this refers to the new jQuery instance being created.
  3. makeArray does 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 length property of the jQuery instance to the number of matched elements, completing the array-like structure.

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 07:43:33