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?
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
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!