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?
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) %>;