如何匹配数组的任何元素?

时间:2012-11-28 18:18:07

标签: javascript arrays

如何检查变量是否等于数组的任何元素?

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!");
        }
};

2 个答案:

答案 0 :(得分:1)

您必须遍历myArray并检查每个元素。

但是,如果您不关心IE 8或更早版本,则可以使用indexOf

答案 1 :(得分:1)

这应该这样做

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");
}