Master Developer
Master Developer

Reputation: 97

Convert ejs variable to javascript variable

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

Upvotes: 2

Views: 2423

Answers (1)

Kristianmitk
Kristianmitk

Reputation: 4778

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]);
}

Upvotes: 3

Related Questions