简体   繁体   中英

jQuery each() loop does not return control when a condition is met

I want return true/false from my function when the if condition is met. However it's not returning true , every time it returns false . Please help me. Thanks.

function catExists(cName) {
  $("#room_has_cat_table tbody tr td:first-child").each(function(index, item) {
    var existingCat = $(this).text();
    alert(existingCat);
    
    if (existingCat == cName) {
      return true;
    }
  });
  
  return false;
}

The problem with your logic is because you cannot return a value from an anonymous function.

To correct your logic define a boolean variable which you can update inside the loop when a match is found:

function foo(cName) {
  let matchFound = false;

  $("#room_has_cat_table tbody tr td:first-child").each(function() {
    var existingCat = $(this).text();
    if (existingCat == cName) {
      matchFound = true;
      return; // exit the each() loop
    }
  });

  return matchFound;
}

However , a better approach entirely would be to use filter() to find the match. This avoids the need for the explicit loop:

let matchFound = $("#room_has_cat_table tbody tr td:first-child").filter((i, el) => el.innerText.trim() === cName).length !== 0;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM