EJS is not allowing primitive digits in the terminating condition in for loops

时间:2018-04-20 01:06:56

标签: node.js express ejs

I am rendering out some data stored in a users object in an EJS template. However, I only want to render the first 40 items, like so:

<% for(var i=0; i<40; i++) { %>
    <% if (users[i].icon_url) { %>
        <a href="<%= users[i].app_download_link %>">
            <img title="<%= users[i].title %>" class="photo" src=<%= users[i].icon_url %>>
        </a>
    <% } %>
<% } %>

Doing so results in an error message stating that Cannot read property 'icon_url' of undefined, where icon_url is a property on the users object.

Changing the above code to:

<% for(var i=0; i<users.length; i++) { %>
    // Same body as above
<% } %>

Works perfectly fine. I've searched quite a bit for this, but have come up empty handed. Am I missing something obvious here?

1 个答案:

答案 0 :(得分:1)

当users.length为&lt; 40.当i等于users.length时,则users [i]计算为undefined。

您可以在视图之外过滤数据,或者您需要检查i&lt;最大值40和users.length。

相关问题