This question already has an answer here:
I need to determine if a value exists in an array.
I am using the following function:
Array.prototype.contains = function(obj) {
var i = this.length;
while (i--) {
if (this[i] == obj) {
return true;
}
}
return false;
}
The above function always returns false.
The array values and the function call is as below:
arrValues = ["Sam","Great", "Sample", "High"]
alert(arrValues.contains("Sam"));
My little contribution:
I prefer simplicity:
Given the implementation of indexOf for IE (as described by eyelidlessness):
Array.prototype.includes()
In ES2016, there is
Array.prototype.includes()
.Example
Support
According to kangax and MDN, the following platforms are supported:
Support can be expanded using Babel (using
babel-polyfill
) orcore-js
. MDN also provides a polyfill:If you have access to ECMA 5 you can use the some method.
MDN SOME Method Link
If you have access to ECMA 6 you can use the includes method.
MDN INCLUDES Method Link