首页 > 解决方案 > ejs变量增量不起作用

问题描述

初始化 ejs 变量后,我无法更改值并且增量运算符不起作用。

这是我的代码:

   <% 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++; 
                        } %>
          <% }); %>
    <% }); %>

在上面的代码中,我声明了一个变量 i 并在底部添加了 i++。

标签: node.jsexpressejs

解决方案


i应该在语句之外forEach声明,否则在每个 cicle 中重新声明

更正上面的代码

<% 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++; 
                        } %>
          <% }); %>
    <% }); %>

推荐阅读