我一直在尝试创建一个包含一组数字的数组。在这种情况下,10,33,55和99.我正在寻找的是灵活的搜索数组中的变量以查看数字是否在其中。
var nrArray = [10, 33, 55, 99]; // Any number in this array will decide the function below
if ( 55 = nrArray ) { // If the number 55 is in the array do the following
document.getElementById("demo1").innerHTML = "RUN1";
}
else { // If the number 55 does not exist in the array do the following
document.getElementById("demo2").innerHTML = "RUN2";
}
<p id="demo1">demo1</p>
<p id="demo2">demo2</p>
请注意 此示例中的55将替换为设置了数字的变量。这个数字会有所不同
答案 0 :(得分:1)
您可以使用Array.prototype.indexOf。如果元素存在于数组中,则indexOf
方法将返回元素的索引,否则返回-1。
var nrArray = [10, 33, 55, 99];
var myVar = 55;
if (nrArray.indexOf(myVar) !== -1) {
document.getElementById("demo1").innerHTML = "RUN1";
} else {
document.getElementById("demo2").innerHTML = "RUN2";
}
<p id="demo1">demo1</p>
<p id="demo2">demo2</p>
答案 1 :(得分:0)
var nrArray = [10, 33, 55, 99]; // Any number in this array will decide the function below
if (nrArray.indexOf(55) > -1 ) { // If the number 55 is in the array do the following
document.getElementById("demo1").innerHTML = "RUN1";
}
else { // If the number 55 does not exist in the array do the following
document.getElementById("demo2").innerHTML = "RUN2";
}
<p id="demo1">demo1</p>
<p id="demo2">demo2</p>