Quiero devolver verdadero/falso de mi función cuando se cumpla la condición if . Sin embargo, no devuelve true , cada vez que devuelve false . Por favor, ayúdame. Gracias.
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; }El problema con su lógica es que no puede return un valor de una función anónima.
Para corregir su lógica, defina una variable booleana que pueda actualizar dentro del bucle cuando se encuentre una coincidencia:
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; } Sin embargo , un mejor enfoque sería usar filter() para encontrar la coincidencia. Esto evita la necesidad del bucle explícito:
let matchFound = $("#room_has_cat_table tbody tr td:first-child").filter((i, el) => el.innerText.trim() === cName).length !== 0;