JarrodOliver JarrodOliver - 1 year ago 63
Javascript Question

How do I get an array to loop x number of times instead of every item?

Currently I have an array that has about 20 records and grows by 1 each month. (Think monthly newsletters). Instead of looping through every one I would just like to loop through the first 10 or 15.

$.each(newArray, function (index, item) {
$('#CommunityNL ul').append("<li>" + "<a href='" + item.FileRef + "'>" + item.Title + "</a>" + "</li>");

I found the splice method and it works perfectly fine by splicing newArray before looping so that newArray only has 10 items in it. I'm not sure if this is the best way to do things though?

Answer Source

From the docs:

We can break the $.each() loop at a particular iteration by making the callback function return false. Returning non-false is the same as a continue statement in a for loop; it will skip immediately to the next iteration.

So you can use something like

$.each(array, function(index, item) {
  if (index == endIndex) return false;
  // Do things

Or just use a normal loop. Why do you need jQuery anyways to iterate an array?

for (var i=0, to=Math.min(array.length, endIndex); i < to; ++i) {
  // Do things with array[i]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download