Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

166
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda