在下面的代碼中,我有一個表單輸入。當用戶搜索恰好在數組中的字符串時,我希望它輸出查詢。當用戶碰巧搜索不在數組中的字符串時,我想輸出一條錯誤消息。問題是當用戶搜索數組中的項[0]以外的字符串(在這種情況下爲ipsum)時,他們收到錯誤消息,然後他們返回查詢。我想知道這是否可以通過使用下面的代碼來補救,或者是否應該採取一種不同的方法來執行此操作(我知道這是一個意見)。在javascript中循環數組時跳過不匹配的字符串
<form>
<input type="text" id="formInput"></input>
<input type = "button" id="search"></input>
</form>
<script>
var search = document.getElementById("search");
var data = ["lorim", "ipsum"];
search.onclick = function(){
var formInput = document.getElementById("formInput").value;
for (i=0; i<data.length; i++){
if (data[i] === formInput) {
alert(data[i]);
}
else{ alert("not working yet"); }
}
};
</script>
感謝。另一個答案是更容易,更重要的,但我讚賞這一點,無論如何。 – William