2016-08-26 82 views
1

我正在爲用戶填寫答案編碼測驗,如果它與數組中的正確答案之一匹配,則該字段將變爲綠色,否則變爲紅色。這是什麼在起作用:如何將輸入值與數組的整個範圍匹配?

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"這是真的。在這種情況下,如何選擇陣列中的所有項目?

+0

增加了一個工作片段,以更清晰的代碼[這裏](http://stackoverflow.com/a/39158841/1409180) – nikjohn

+1

'bkgColor = arr.includes(id.value)? 「綠色」:「紅色」 – Redu

回答

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

循環不是最乾淨的方法,當有像javascript'filter'功能的東西時IMO – nikjohn

+0

非常感謝你,結果非常好! – Andy

+0

A'break;'也會有所幫助。 –

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

檢查出來了,沒有爲我工作:(但是thanx爲你的努力 – Andy

0

一個實現這種更清潔的方式如下:

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>

+0

達斯汀,這個片斷其實已經在函數中了,我只是懶得給所有圖片,它會像函數裏面的函數那樣工作嗎? – Andy

+0

我didn大多數函數都可以嵌套在JS的函數中 我的建議是在數組中使用'filter'函數,它比運行循環更清晰(這是因爲性能不佳而臭名昭着)甚至更好,你可以使用像'Array.prototype.includes' – nikjohn

+0

剛剛檢查出來,它沒有在我的情況下工作 – Andy