2
<body>
<% var a = ["1","2","3","4"]
<% var i = 0 %>
<script>
   var n = "<% a.length %>"
   for(var i=0;i<n;i++){
      console.log("<%= a[i] %>")
   }
</script>
</body>

In the above code I want that the "i" of a[i] should get incremented after each iteration.For this I have to change the ejs "i" to the javascript variable and then increment it.Is there any way to increment the ejs "i" under javascript tag????Or any other method for getting the above result??

1 Answer 1

3

This wont work like you are trying it as you cannot access the ejs variables at that point anymore. What you could to is to pass the a-array to your browser js.

This can be archived with:

var n = <%-JSON.stringify(a)%>;

So your code would look like:

var n = <%-JSON.stringify(a)%>;
for(var i=0 ;i < n; i++){
  console.log(n[i]);
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks you save my day
@PiyushKumar Please mark the answer as correct; it saved your day after all :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.