user4434001
user4434001

Reputation:

How stop a looping in the fourty loop

I'm pulling data from my database, and sending for my views through my controllers. The date is coming, and I'm rendering this data in the HTML with a looping.

The problem is that I want to show only 4 items, not all. How can I solve this?

For example:

<% for(var i = 0; i < data.length; i++ { %>
 <p> <%= data[i].name %>
 <p> <%= data[i].age %>
<% } %>

I want only render 4 times. How achieve this?

Thanks!

Upvotes: 0

Views: 52

Answers (2)

TheIronDeveloper
TheIronDeveloper

Reputation: 3624

I would do something like:

<% for(var i = 0,max = (data.length > 4 ? 4 : data.length); i < max; i++ { %>
 <p> <%= data[i].name %>
 <p> <%= data[i].age %>
<% } %>

What this does is iterate the loop either 4 times or the length of data (whichever is shorter). If you don't have that conditional, you might get into an index out of bounds (if data.length is 2, for example).

Coding note: its good practice to declare max at the beginning of the for-loop. Its more readable and, for performance sakes, the lookup of the length attribute of data only happens once (instead of each iteration).


Update based on comments

To add other conditionals (such as if the pageName = 'home')

<% for(var i = 0,max = ( (data.length > 4 && pageName === 'home') ? 4 : data.length); i < max; i++ { %>
 <p> <%= data[i].name %>
 <p> <%= data[i].age %>
<% } %>

Upvotes: 0

Hiten Naresh Vasnani
Hiten Naresh Vasnani

Reputation: 538

Like this:

<% for(var i = 0; i < data.length && i<4; i++ { %>
 <p> <%= data[i].name %>
 <p> <%= data[i].age %>
<% } %>

Upvotes: 1

Related Questions