eow2898 eow2898 - 1 year ago 69
jQuery Question

How to test whether a variable is equal to one of five Array Values

I am storing five values in an array and I need to check whether a variable I've set up is equal to one of those values. Here is what I mean:

var x = e.clientX, // horizontal mouse position
myArray = []; // I have another function that stores five values in this array

if(x == /*one of the five array values*/){
//do something


Answer Source

You can use Array.prototype.includes, which checks if the array includes the value. Note that this is not supported on Internet Explorer, you can find the polyfill at the mentioned link. Per the documentation:


The includes() method determines whether an array includes a certain element, returning true or false as appropriate.

if(myArray.includes(x)) {
    //x is in myArray

If you want the position, you may use indexOf:


This will search for item and return the position. If not found, it will return -1. This can be applied to work with IE:

if(myArray.indexOf(x) > -1) {
    //x is in myArray

This makes sure it exists because it checks if the position is greater than -1.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download