JavaScript Array Contains

Avatar of Chris Coyier
Chris Coyier on

Javascript objects are really nice, but sometimes they are missing some useful little functions/methods. The example above is with Arrays. It’s really nice to know whether or not an item is contained within your array. Well you can write a function that takes the array and the item you’re checking for, but it’s much cleaner to add the contains( item ) method to the Array object.

Extending JavaScript Arrays

/**
 * Array.prototype.[method name] allows you to define/overwrite an objects method
 * needle is the item you are searching for
 * this is a special variable that refers to "this" instance of an Array.
 * returns true if needle is in the array, and false otherwise
 */
Array.prototype.contains = function ( needle ) {
   for (i in this) {
       if (this[i] == needle) return true;
   }
   return false;
}

Usage

// Now you can do things like:
var x = Array();
if (x.contains('foo')) {
   // do something special
}