如何检查变量是否等于数组的任何元素?
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!");
}
};
答案 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");
}