gpt4 book ai didi

javascript - 如果数组有特定值

转载 作者:行者123 更新时间:2023-12-03 11:23:34 26 4
gpt4 key购买 nike

我一直在尝试创建一个包含一组数字的数组。在本例中是 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.indexOfindexOf 方法将返回元素的索引(如果该元素存在于数组中),否则返回 -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>

关于javascript - 如果数组有特定值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27011366/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com