Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reason for .get() without index in jQuery API?

Let's say that I've got a page which extracts some image sources like so:

<div id="d">
  <img src="foo.gif"/>
  <img src="bar.gif"/>
  <img src="gah.gif"/>
</div>
<script type="text/javascript">
  var srcs = $('div#d > img').map(function(){return this.src});
  // srcs => ['foo.gif', 'bar.gif', 'gah.gif']
</script>

Note that srcs is not a JavaScript Array but an array-like object; we know this because of the fact that we can make jQuery API calls on objects returned by the selector and the fact that srcs.constructor != Array.

The jQuery API provides a .get() method which, when given no argument, returns a "standard" Array. Is there a compelling reason to use a standard Array instead of an array-like object or is this method just included for completeness?

[Edit]

To put it another way - what are the differences between a JavaScript Array and the array-like object returned by a jQuery selector?

like image 203
maerics Avatar asked Jun 06 '11 15:06

maerics


People also ask

How to Get index element in jQuery?

jQuery Misc index() Method The index() method returns the index position of specified elements relative to other specified elements. The elements can be specified by jQuery selectors, or a DOM element. Note: If the element is not found, index() will return -1.

How do you select an element by index?

The :eq() selector selects an element with a specific index number. The index numbers start at 0, so the first element will have the index number 0 (not 1). This is mostly used together with another selector to select a specifically indexed element in a group (like in the example above).

Which of the following functions helps select the first element from the list of selected elements by the jQuery function?

The :first selector selects the first element. Note: This selector can only select one single element. Use the :first-child selector to select more than one element (one for each parent).

What is the meaning of in jQuery?

Basic syntax is: $(selector).action() A dollar sign to define jQuery. A (selector) to "query (or find)" HTML elements. A jQuery action() to be performed on the element(s)


2 Answers

It allows you to use standard array methods which jQuery doesn't have, such as push.

In particular, jQuery objects are intended to be immutable, whereas arrays are not.

like image 176
SLaks Avatar answered Sep 27 '22 17:09

SLaks


Main advantage of get is enabling negative indexes like -1 for getting last element. No argument just gets you the raw unwrapped array of matched elements.

like image 21
Z. Zlatev Avatar answered Sep 27 '22 19:09

Z. Zlatev