0

How do I check if a variable is equal to any element of an array?

var myButton = document.getElementById("myButton");
var myVar; //myVar value is set to "One", "Two" or "Three" sometime later

myArray = ["One","Two","Three"];

myButton.onclick = function () {
    if (myVar === myArray) {
        alert ("it's a match!");
    } else {
                alert ("it's not a match!");
        }
};
Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
badmidget
  • 53
  • 1
  • 7

2 Answers2

1

You have to loop through myArray and check each element.

However, you can use indexOf if you don't care about IE 8 or earlier.

Daniel A. White
  • 187,200
  • 47
  • 362
  • 445
  • Forgive me, I'm new to javascript, but when I hear people say that I normally see them do something like: `var myArrayLength = myArray.length;` but from what I can tell that only makes myArrayLength = 3. I guess I don't know what to do with that. – badmidget Nov 28 '12 at 18:23
  • 2
    @user1860777 I don't understand how this relates to the question or this answer. – phant0m Nov 28 '12 at 18:29
  • As I said, I'm new to javascript so I appreciate the info you provided. For now, I did it the oldschool way described by Bruno, but I'm happy to now know about indexOf. I'm sure I'll be using it soon. – badmidget Nov 29 '12 at 15:34
1

This should do it

myButton.onclick = function () {
    var i = myArray.length;
    while( i-- ) {
        if( myVar === myArray[i] ) {
            alert("it's a match");
            return;
        }
    }
    alert("it's not a match");
}
Bruno
  • 5,772
  • 1
  • 26
  • 43