Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

171
Visualizações
Foreach loop to check for a value

I have a foreach loop that loops through an array, then im running a callback function with the value of each item in the array as the parameter of the function, which is run once fore very item in the array. In the call back function i am trying to compare the value being passed with a string, but I always get a false nothing gets logged to console

This is my code

window.addEventListener('load', function() {
  let occupation = ["urologist", "urologist", "staff", "nurse", "surgeon"]

  occupation.forEach(function(occ) {
    let ab = occ.textContent
    let bc = ab.toLowerCase();
    chkfun(bc)
  })

  function chkfun(val) {
    if (val == "urologist") {
      console.log("urologist")
    }
    if (val == "surgeon") {
      console.log("surgeon")
    }
    if (val == "staff") {
      console.log("staff")
    }
    if (val == "nurse") {
      console.log("nurse")
    }
  }
}, false);

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Your problem is with the line let ab = occ.textContent. occ contains the text content already. You can just do bc = occ.toLowerCase()

Also take a look at JavaScript Switch instead of doing a bunch of if's

about 4 years ago · Juan Pablo Isaza Relatório

0

You can call your function inside the forEach and it will be called with each element, there you can transform your value to lowercase and compare, also use a else if so the script will not test each value and stop as soon as it get a match. You can also add a else at the end for unknown elements

window.addEventListener('load', function() {
  let occupation = ["Urologist", "urologist", "staff", "nurse", "surgeon","a"];
  occupation.forEach(chkfun);
  function chkfun(v) {
    let val = v.toLowerCase();
    if (val == "urologist") {
      console.log("urologist")
    } else if (val == "surgeon") {
      console.log("surgeon")
    } else if (val == "staff") {
      console.log("staff")
    } else if (val == "nurse") {
      console.log("nurse")
    } else {
      console.log("element not found");
    }
  }
}, false);

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda