簡體   English   中英

遍歷數組后無法顯示警報

[英]Trouble showing alert after iterating through an array

我有一個輸入字段,用戶在其中輸入他們的郵政編碼,然后我嘗試將其匹配到數組中的郵政編碼。 盡管以下內容有效,但我需要它實際上顯示一個警告對話框,提示說未找到郵政編碼,但是,即使列表中包含郵政編碼,它也會彈出很多對話框。

這是我的片段:

_zipcodeBtn.onclick = function(){
  var userZip = _zipcode.value;

  for (var i = 0; i < zipcode_list.length; i++) {
    if (zipcode_list[i] === userZip) {
      console.log('works');
      break;
    } else {
      alert("repeating");
    }
  }
};

我希望它檢查是否有可用的zip,而無需多次重復else語句。 預防這種情況的最佳方法是什么?

通過引用數組的indexOf()方法( docs ),可以找到一種在數組中查找項目的簡便方法。

if (zipcode_list.indexOf(userZip) != -1) {
    //found - do something
} else
    alert('Zip not found!');

如Angel Politis所示,如果您只是想知道某項是否在數組中,而不是其在數組中的實際位置,則也可以使用includes()

旁注:使用indexOf()時檢查-1很重要,因為它返回找到搜索的索引;否則返回-1。 如果在第一個鍵處找到了搜索,則該值為0,並且0為一個偽造的值,當人們執行以下操作時,該值有時會使其誤入歧途:

var arr = [1, 2, 3];
if (arr.indexOf(1))
    alert('success');
else
    alert('failed');

您可能會認為成功警報將在此處觸發,但實際上它將是失敗警報,因為在這種情況下, indexOf()返回0,並且在有條件的情況下被查詢時,0是偽造的值。

此處無需使用循環。 您可以說:

if (!zipcode_list.includes(userZip)) alert("Doesn't work!");

如果必須使用循環,則只需在默認情況下將標志設置為false ;如果找到了zip,則將其設置為true 然后,您可以在循環外檢查它:

/* Create a flag and set it by default to false. */
var found = false;

/* Loop */
for (var i = 0, l = zipcode_list.length; i < l; i++) {
  if (zipcode_list[i] === userZip) {
      /* Set the flag to true and stop the loop. */
      found = true;
      break;
  } 
}

 /* Check whether the zip was found in the array. */
 if (found) console.log("Works!");
 else alert("Doesn't work!");

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM