NodeSaiyan NodeSaiyan - 23 days ago 13
Node.js Question

How could you solve this node.js error of undefined property?

I have this error message of

Cannot read property 'title' of undefined

It worked fine when I used posts.forEach for traversing. but
It stopped working when used with for loop.
Could you please help?

This is my code

<section class="forum">
<ul class="pages">
<% for (var i = 1; i <= Math.ceil(posts.length / 3); i++) { %>

<li><a href="#<%=i%>"><%= i %></a></li>

<% } %>
<% var pages = i %>

</ul>
<div class="tabbedPages">
<div class="tabbedPage">

<% for (var i = 1; i <= pages; i++) { %>
<div class="page" id="<%=i%>">
<table>
<tr>
<th>Title</th>
<th>Replies</th>
<th>Last Message</th>
</tr>
<% for (var j = (i - 1) * 3; j < (i * 3) ; j++){ %>
<tr>
<td>

<h2><%= posts[j].title %></h2>
<h2><%= posts[j].author %>,
<% var diff = posts[j].date - Date.now %>
<% var msec = diff
var dd = Math.floor(msec / 1000 / 60 / 60 / 24);
msec -= dd * 100 * 60 * 24;
var hh = Math.floor(msec / 1000 / 60 / 60);
msec -= hh * 1000 * 60 * 60;
var mm = Math.floor(msec / 1000 / 60);
msec -= mm * 1000 * 60;
var ss = Math.floor(msec / 1000);
msec -= ss * 1000;
%>
<% if (dd >= 1) { %>
<%= dd %> days ago
<% } else if (hh >= 1) { %>
<%= hh %> hours ago
<% } else if (mm >= 2) { %>
<%= mm %> minutes ago
<% } else if (mm == 1) { %>
1 minute ago
<% } else { %>
Moments ago
<% } %>

</h2>
</td>
<td>
<h2>Replies: <%= posts[j].posts.length%></h2>



</td>
<td>
<h2>
<% if (posts[j].posts.length == 0 ) { %>
Not Available Yet
<% } else { %>
<%= posts[j].posts[posts[j].posts.length - 1].author %>
<% } %>
</h2>
<h2>
<% var diff = posts[j].date - Date.now %>
<% var msec = diff
var dd = Math.floor(msec / 1000 / 60 / 60 / 24);
msec -= dd * 100 * 60 * 24;
var hh = Math.floor(msec / 1000 / 60 / 60);
msec -= hh * 1000 * 60 * 60;
var mm = Math.floor(msec / 1000 / 60);
msec -= mm * 1000 * 60;
var ss = Math.floor(msec / 1000);
msec -= ss * 1000;
%>
<% if (dd >= 1) { %>
<%= dd %> days ago
<% } else if (hh >= 1) { %>
<%= hh %> hours ago
<% } else if (mm >= 2) { %>
<%= mm %> minutes ago
<% } else if (mm == 1) { %>
1 minute ago
<% } else { %>
Moments ago
<% } %>
</h2>
</td>

</tr>

<% } %>

</table>

<% } %>
</section>


Could you please help me what the heck is wrong with this code?

Answer

You want 3 posts per page, but the last page may also have 1 or 2 posts. So you need to add another check:

<% for (var j = (i - 1) * 3; j < (i * 3) && j < posts.length ; j++){ %>
Comments