簡體   English   中英

if 和 else 語句都在執行

[英]If and else both statement executing

我正在遍歷數據庫中的所有條目並使用 if 條件來檢查 departmentID 是否與我給定的 ID 匹配。 問題是當 If 條件為真時,它也會運行 else 條件,但當條件為假時,它只運行 else 部分,這很好。

$.ajax({
  url: "php/getall.php",
  type: 'GET',
  dataType: 'json',
  success: function(result) {
    employees = result['data'];
    console.log(employees);

    employees.forEach((employee) => {
      if (employee.departmentID === deptid) {
        $('#preventdel').modal('show');
      } else {
        $('#confirmdel').modal('show');
      }
    })
  }
})

如果條件為真,它會顯示兩種模態,但如果不滿足條件,則它可以正常工作

if 和 else 都在執行,如果條件立刻滿足就想退出循環

您正在一個循環中執行代碼,因此模式應該與員工中的元素一樣多,因為您使用的是 if-else 語句。 因此,這兩個代碼塊之一將為每個元素執行。

const hasEmployee = employees.some(employee => employee.departmentID === deptid);
    
if (hasEmployee) {
  $('#preventdel').modal('show');
} else {
  $('#confirmdel').modal('show');
}

通過使用some()方法,您可以檢查搜索的元素是否存在於結果中。 然后最后只打開一次模態。

暫無
暫無

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

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