Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

238
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!