Wednesday, January 11, 2012

JavaScript Array Contains

Extending JavaScript Arrays
 

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

Usage
 

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

Labels:

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home