Home >Web Front-end >JS Tutorial >How Can I Efficiently Check if an Array Contains a Specific Value?
Determining Array Value Existence
The query concerns determining whether an element exists within an array. The provided function, Array.prototype.contains, fails to identify elements accurately.
To address this issue, consider utilizing jQuery's utility function: $.inArray. This function accepts two parameters: the value to search for and the array to search within. It returns the index of the value in the array if found. Conversely, it returns -1 if the value is absent.
For instance, given the following array:
arrValues = ["Sam","Great", "Sample", "High"]
To determine if the array contains "Sam", the following code snippet can be used:
var index = $.inArray("Sam", arrValues);
If the element is found, index will contain its position in the array (0 in this case). Otherwise, index will be -1.
Additionally, for more information on checking if an array includes an object, refer to the resource provided in the response.
The above is the detailed content of How Can I Efficiently Check if an Array Contains a Specific Value?. For more information, please follow other related articles on the PHP Chinese website!