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

240
Vistas
NodeJS/ Express/EJS: Cannot get length of JSON Array rendered from NodeJS in Javascript

Firstly, I would like to mention that I'm able to get the correct length of data if I put the for loop inside EJS, but the same thing doesn't work in Javascript.

My code in ejs file:

<% for(var i=0; i< arr.length; i++){ %>
      TESTING
<% } %> 

This will display TESTING for 3 times, which is correct. However, when I run the loop in Javascript, it gives me 40++ outputs.

My code in same ejs file:

<script>
var newArr = "<%- arr%>";

 for(var i=0; i< newArr.length; i++){ 
      $(document).ready(function() {
           setData();
      });
 }

 function setData(){
     var box = document.getElementById('list-box');
     const para = document.createElement('p');
     para.innerHTML = `<input type="button" value="Test">`
     box.appendChild(para);
 }
</script>

Over 40 paragraphs are appended here...I have no idea why the length can be different (there is no error at all). May someone teach me on method of getting length in javascript?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

newArr is a string and newArr.length is the number of characters. Remove the quotes and stringify the array before:

var newArr = <%- JSON.stringify(arr) %>;
about 4 years ago · Juan Pablo Isaza 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