JavaScript determines whether an array contains the specified element
- 2020-06-22 23:54:38
- OfStack
This article shows how JavaScript determines whether an array contains a specified element. Share to everybody for everybody reference. The details are as follows:
This code defines the array method through prototype, so you can call the contains method from any array
/**
* 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
}
Hopefully, this article has helped you with your javascript programming.