10

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?

1

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.