如果数组具有特定值

If array has a specifc value

本文关键字:数组 如果      更新时间:2023-09-26

我一直在尝试创建一个包含一组数字的数组。在本例中为 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 将替换为设置了数字的变量。这个数字会有所不同

您可以使用 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>
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>