inArray Method for JavaScript
by senthil[ Edit ] 2007-11-16 12:16:41
This method (prototype) provides simple linear search capabilities for the built-in array class of JavaScript and ActionScript (ECMAScript compatible). It will return true or false depending upon whether the value passed as an argument to the method is found within the array object.
Note that the method searches for an identical value, rather than a similar value. In other words, the string "003" should not match the integer 3. This could be changed by replacing "===" in the method with"==".
if (myList.inArray('search term')) {
// Found it!
}
This function should work fairly well on relatively small lists of items. For a larger array, a binary search function may be more appropriate.
Array.prototype.inArray = function (value)
// Returns true if the passed value is found in the
// array. Returns false if it is not.
{
var i;
for (i=0; i < this.length; i++) {
// Matches identical (===), not just similar (==).
if (this[i] === value) {
return true;
}
}
return false;
};