如果数组具有特定值
If array has a specifc value
我一直在尝试创建一个包含一组数字的数组。在本例中为 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>
相关文章:
- 如果在代码末尾进行求值,jQuery-console.log将提供空数组
- 如果数组仍在执行,async.forEach()将运行我添加到数组中的新元素
- underline-js:将键对象与数组键对象进行比较,如果存在,则移除现有的添加新的
- Javascript:如果数组有对象或不为空
- 根据条件将函数放入数组中(如果选中复选框)
- 如果输入包含数组中的任何单词
- 如果值包含数组中的一个或多个
- JavaScript 如果数组包含名称,则不要这样做
- 如果我知道另一个值,请在多维数组中查找一个值
- 如果数组包含特定值,则返回该值的完整“内容”
- 如果在数组中发现重复,则必须通过纯javascript添加带关键字的索引
- 如果's的第一个非空数组
- 如果字符串中存在错误,请检查数组中的char
- 如果我只想从数组中打印任何一个元素.任何数组.那么代码会是什么
- 从数组中删除值,用新的数组总数更新html或'$'如果没有总计
- 如果数组中的值为false,则破坏Promise
- MD 数组:如果未找到值,则添加其他数组
- Rethinkdb追加到数组如果存在
- Javascript:循环数组.如果找到匹配项,则推送到数组,如果没有,则创建新的innerarray
- Javascript字符串到数组(如果字符串没有任何空格)