Home >Web Front-end >JS Tutorial >Why Does My Array Contains Function Always Return False, and How Can I Reliably Check for Values in JavaScript Arrays?

Why Does My Array Contains Function Always Return False, and How Can I Reliably Check for Values in JavaScript Arrays?

Susan Sarandon
Susan SarandonOriginal
2024-12-15 03:14:09827browse

Why Does My Array Contains Function Always Return False, and How Can I Reliably Check for Values in JavaScript Arrays?

How to Check for Value in an Array

Determining whether a specific value exists in an array is a common programming task. However, when using the following custom function:

Array.prototype.contains = function(obj) {
    var i = this.length;
    while (i--) {
        if (this[i] == obj) {
            return true;
        }
    }
    return false;
}

you may encounter unexpected behavior (always returning false). This is because the function relies on strict equality (==) comparisons, which can fail in certain cases (e.g., numbers that are considered equal but not identical).

A Robust Solution Using jQuery

For reliable value checks in arrays, consider using jQuery's utility function:

$.inArray(value, array)

This function searches the array for the specified value. If the value is found, it returns its index within the array. If the value is not found, it returns -1.

Example Usage

var arrValues = ["Sam","Great", "Sample", "High"];
var value = "Sam";

var result = $.inArray(value, arrValues);

if (result !== -1) {
    // Value found in array
} else {
    // Value not found in array
}

Additional References

  • [How do I check if an array includes an object in JavaScript?](https://stackoverflow.com/questions/1232040/how-do-i-check-if-an-array-includes-an-object-in-javascript)

The above is the detailed content of Why Does My Array Contains Function Always Return False, and How Can I Reliably Check for Values in JavaScript Arrays?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn