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"));
tl;dr
Example
Longer Answer
I know this question isn't really about whether or not to extend built-in objects, but the attempt of the OP and the comments on this answer highlight that debate. My comment from Feb 12, '13 cites an article that outlines this debate really well, however that link broke and I can't edit the original comment because too much time has passed, so I include it here.
If you're looking to extend the built-in
Array
object with acontains
method, probably the best and most responsible way to do this would be to use this polyfill from MDN. (See also this section of the MDN article on Prototypical inheritance, which explains that "The only good reason for extending a built-in prototype is to backport the features of newer JavaScript engines; for example Array.forEach, etc.")Don't want strict equality, or want to choose?
Since ECMAScript6, one can use
Set
:You can use it like this:
CodePen validation/usage
The simplest solution for a
contains
function, would be a function that looks like this :Ideally, you wouldn't make this a stand-alone function, though, but part of a helper library :
Now, if you happen to be one of those unlucky people who still needs to support IE<9 and thus can't rely on
indexOf
, you could use this polyfill, which I got from the MDN :jQuery has a utility function for this:
Returns index of
value
inarray
. Returns-1
ifarray
does not containvalue
.See also How do I check if an array includes an object in JavaScript?
This is generally what the indexOf() method is for. You would say: