jQuery in Action
Manipulating JavaScript objects and collections
175
jQuery's support for arrays doesn't stop there. There are a handful of minor
functions that we might find handy.
6.3.5 More fun with JavaScript arrays
Have you ever needed to know if a JavaScript array contained a specific value
and, perhaps, even the location of that value in the array?
and, perhaps, even the location of that value in the array?
If so, you'll appreciate the
$.inArray()
function
A trivial but illustrative example of using this function is
var index = $.inArray(2,[1,2,3,4,5]);
This results in the index value of 1 being assigned to the
index
variable.
Another useful array-related function creates JavaScript arrays from other
array-like objects.
"Other array-like objects? What on Earth is an array-like object?" you may ask.
jQuery considers other array-like objects to be any object that has a length and
jQuery considers other array-like objects to be any object that has a length and
the concept of indexed entries. This capability is most useful for
NodeList
objects.
Consider the following snippet:
var images = document.getElementsByTagName("img");
This populates the variable
images
with a
NodeList
of all the images on the page.
Dealing with a
NodeList
is a bit of a pain, so converting it to a JavaScript array
makes things a lot nicer. The jQuery
$.makeArray
function makes converting the
NodeList
easy.
Function syntax: $.inArray
$.inArray(value,array)
Returns the index position of the first occurrence of the passed value
Parameters
value
(Object) The value for which the array will be searched
array
(Array) The array to be searched
Returns
The index of the first occurrence of the value within the array or -1 if the value is not found
The index of the first occurrence of the value within the array or -1 if the value is not found