Determine whether an array contains a value [duplicate]

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"));

1
18

This is generally what the indexOf() method is for. You would say:

return arrValues.indexOf('Sam') > -1

Leave a Comment