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

239
Visualizações
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 Respostas
Responde à pergunta

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 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