Created
May 1, 2012 19:08
-
-
Save Boztown/2570569 to your computer and use it in GitHub Desktop.
Javascript: Array Contains
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment