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

163
Visualizações
How to make a loop in a javascript function using EJS

I've written this script. It works fine, but when I'm adding the loop it doesn't work. Is there a mistake in the structure of the loop or another thing?

<p id="f"></p>
<script>
    var resultat = '{ "name":"multiplication matricielle", "age":30, "city":"New York"}'
    var obj = JSON.parse(resultat);
    document.getElementById("id1").value = obj.name;
    document.getElementById("id2").value = obj.age;
    document.getElementById("id3").value = obj.city;
</script>


<script>
    function compare() {
        a = "yes";
        var i;
        for (i = 0; i < '<%=inf.length%>'; i++) {

            if ('<%=inf[i].nom%>' == obj.name && '<%=inf[i].sortie%>' == obj.city) {
                return a;
            }
        }
    }
    document.getElementById('f').innerHTML = compare();
</script>
about 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

You have to return outside of your loop and you can change a little:

function compare() {
  var a = "No"; // <---initialize with default value
  var i;
  for (i = 0; i < parseInt('<%=inf.length%>', 10); i++) { // parse as number
    if ('<%=inf[i].nom%>' == obj.name && '<%=inf[i].sortie%>' == obj.city) {
      a = "Yes"; // if check is true change the value
    }
  }
  return a; // <--- now return it here
}

For your comment:
You need to parse a string number to a valid number

parseInt('<%=inf.length%>', 10); // You have to parse it as number.
about 4 years ago · Santiago Trujillo 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