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

How to match an input value to the whole range of an array?

本文关键字:数组 范围 输入      更新时间:2023-09-26

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

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";

创建一个标志变量,当它与数组中的项匹配时设置。然后检查此标志以确定是将背景色设置为绿色还是红色。

示例代码:

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

一种更简洁的实现方式如下:

function evaluateAnswerFilter() {
  var arr = ["a", "b", "c"];
  var inputEl = document.getElementById("id");
  var truth = arr.filter(function(option) {
    return option === inputEl.value
  });
  truth.length ? inputEl.style.backgroundColor = "#83C183" :
    inputEl.style.backgroundColor = "#E06969"
}
function evaluateAnswerIncludes() {
  var arr = ["a", "b", "c"];
  var inputEl = document.getElementById("id");
  arr.includes(inputEl.value) ? inputEl.style.backgroundColor = "#83C183" :
    inputEl.style.backgroundColor = "#E06969"
}
<body>
  <input name="id" id="id" type="text" />
  <button onclick="evaluateAnswerFilter()">Evaluate with Filter</button>
  <button onclick="evaluateAnswerIncludes()">Evaluate with Includes</button>
</body>