如何将输入值与数组的整个范围相匹配?

时间:2016-08-26 05:06:11

标签: 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"为真。在这种情况下,如何选择阵列中的所有项目?

3 个答案:

答案 0 :(得分:1)

创建一个标志变量,只要它与数组中的项匹配就会设置。然后检查此标志以确定是否将背景颜色设置为绿色或红色。

示例代码:

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

答案 1 :(得分:1)

您只需使用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";

答案 2 :(得分:0)

实现这一目标的更简洁方法如下:

&#13;
&#13;
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"
}
&#13;
<body>
  <input name="id" id="id" type="text" />
  <button onclick="evaluateAnswerFilter()">Evaluate with Filter</button>
  <button onclick="evaluateAnswerIncludes()">Evaluate with Includes</button>

</body>
&#13;
&#13;
&#13;