JQuery: utility functions VI – checking if an item is in an array

In the last post we’ve seen how to get all the items that comply with a specific filter. In this post, we’re going to see how to see if an item is in an array. The easiest way to do that is to use the inArray function. Take a look at the following snippet:

var arr = [0, -2, 4, 6, - 9];
var positives = $.inArray(4,arr);

The inArray method expects two parameters: the item that is going to be checked and the array that is going to be enumerated. Internally, the utility function relies on the the === operator for seeing if any of the array’s items matches the first parameter.

Notice that inArray returns an integer. It will return  non negative integer that represents the position of the passed item. If it doesn’t find a matching item, it will simply return –1. And that’s it. Keep tuned for more on JQuery.

Advertisements

~ by Luis Abreu on August 10, 2009.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: