node.js - ejs 变量增量不起作用

标签 node.js express 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++。

最佳答案

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

关于node.js - ejs 变量增量不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50775713/

相关文章:

javascript - 服务器不渲染 ejs 文件

express - 如何使具有路由功能的 Vue.js 应用程序在 Heroku 中工作?

node.js - 使用 Parse.com Express.js 将 .ejs 扩展名更改为 .html

javascript - 如何检查用户是否已经关注 NodeJs 中的其他用户 - Mongoose

javascript - 如何在带有 Node.js Commander 的 repl/bash 中继续接收异步 console.log 消息?

javascript - 按类名称收集元素,然后单击每个元素-Puppeteer

node.js - 检查redis是否正在运行-> node js

android - 服务器更新设备未使用

javascript - 如何在 NodeJs 中使用请求进行多个 API 调用?

node.js - 为什么ejs模板中的分号会抛出错误