SK Media
SK Media

Reputation: 33

ejs variable increment not working

After initialize ejs variable, i cant change value and increment operator not working.

Here is my code:

   <% results1.forEach(function(result1, index){ %>
         <% results2.forEach(function(result2, index1){ %>
                     <% if(result1.id==result2.parent)
                        { 
                           var i=1; %>
                            <tr>
                              <td><%= index+1 %>.<%= i %></td>
                              <td><%= result2.title %></td>
                              <td><%= result1.title %></td>
                              <td align="center"><%= result2.views %></td>

                            </tr>
                          <%  i++; 
                        } %>
          <% }); %>
    <% }); %>

In the above code I declared a variable i and bottom I added i++.

Upvotes: 1

Views: 2566

Answers (1)

Simone Sanfratello
Simone Sanfratello

Reputation: 1610

i should be declared outside forEach statement, otherwise is redeclared at every cicle

correct the code as above

<% results1.forEach(function(result1, index){ %>
         <% var i=1; results2.forEach(function(result2, index1){ %>
                     <% if(result1.id==result2.parent)
                        { 
                            <tr>
                              <td><%= index+1 %>.<%= i %></td>
                              <td><%= result2.title %></td>
                              <td><%= result1.title %></td>
                              <td align="center"><%= result2.views %></td>
                            </tr>
                          <%  i++; 
                        } %>
          <% }); %>
    <% }); %>

Upvotes: 2

Related Questions