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?
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.
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).
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).
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)
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With