javascript - 如何将输入值匹配到数组的整个范围?

标签 javascript arrays loops input

我正在编写一个测验,用户应该在其中填写答案,如果它与数组中的正确答案之一匹配,则该字段变为绿色,否则变为红色。这是有效的:

var arr = ["a", "b", "c"];
var id = document.getElementById("id");
 if (id.value == arr[0] 
     || id.value == arr[1] 
     || id.value == arr[2] 
     || id.value == arr[3]){id.style.backgroundColor = "#83C183";}
     else {id.style.backgroundColor = "#E06969";}

但我想摆脱:

 if (id.value == arr[0] || id.value == arr[1] || id.value == arr[2] || id.value == arr[3])

我尝试用 for 循环迭代数组:

 var arr = ["a", "b", "c"];
 var id = document.getElementById("id");
 for (var i = 0; i < arr.length; i++){ 
      if (id.value == arr[i]){id.style.backgroundColor = "#83C183";}
      else {id.style.backgroundColor = "#E06969";}
      }

但它只返回 "c" 为真。在这种情况下,如何选择数组中的所有项目?

最佳答案

您可以简单地使用indexOf 方法来检查答案是否存在于数组中。

var arr = ["a", "b", "c"];
var id = document.getElementById("id");
if(arr.indexOf(id.value) > -1)
 id.style.backgroundColor = "#83C183";
else  
 id.style.backgroundColor = "#E06969";

关于javascript - 如何将输入值匹配到数组的整个范围?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39158627/

相关文章:

javascript - 单击单元格上的事件而不是整行 - 使用 FIDDLE

javascript - 如何在节点处将HTML代码添加到D3树形图?

javascript - jQuery 隐藏和显示 - 在我单击它之前覆盖图像 "runs"

javascript - 无需页面刷新即可启用地理定位?

javascript - 如何获取所有 LI UL 元素 ID 值并将它们放入 JavaScript 数组中?

arrays - 如何改进Increasing Subsequences算法以合并未排序的数组?

c++ - 打印这个矩阵的 if 语句是什么

python - 创建一个类,通过读取多个 CSV 文件创建字典 - Python

arrays - 在 bash 中循环遍历数组

ruby-on-rails - 在不使用双循环的情况下如何做到这一点?