JavaScript method for determining whether an array contains a specified Element
This example describes how to use JavaScript to determine whether an array contains a specified element. Share it with you for your reference. The details are as follows:
This Code defines the array method through prototype, so that the contains method can be called in any array.
?
| 1 2 3 4 5 6 7 8 9 10 11 12 |
/** * Array. prototype. [method name] allows you to define/overwrite an objects method * Needle is the item you are searching * 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:
?
| 1 2 3 4 5 |
// Now you can do things like: Var x = Array (); If (x. contains ('foo ')){ // Do something special } |
I hope this article will help you design javascript programs.