charliebrown1
charliebrown1

Reputation: 21

Restart a for loop after the end of an array

I working in JavaScript and am trying to add some images to a site.

I have a list of blog posts on a page. And I have a bunch of small stand-alone images (think small icon images) that I want to place on either side of the blog post feed. They are kind of just like random background images. As the feed gets longer, more images will automatically be placed.

Here is some example code of what I have so far. Right now I am just appending text to the page to get this working.

I need help figuring out how to restart this loop once the end of the array is reached. For example, after 6url.jpg is printed, I want to print 1url.jpg and so on if my imageCount is more than 6. I played around with continue and while loops but not sure how to implement that.

var blogIcons = ["1url.jpg", "2url.jpg", "3url.jpg", "4url.jpg", "5url.jpg", "6url.jpg"];
var blogFeedHeight = $(".blog-feed").height();
var imageDistance = 400; 
// Determining how many images to place based on the blog feed height;
var imageCount = Math.ceil(blogFeedHeight/imageDistance); 
// the number of images that should be inserted.
for(var i = 0; i < imageCount; i++){
    $('blog-feed').append('<div class="blog-icon">' + blogIcons[i] +'</div>')
}

Upvotes: 1

Views: 842

Answers (2)

VLAZ
VLAZ

Reputation: 28970

You don't need to restart a loop. Instead you can use modulo division to fetch an item within bounds from the array

var blogIcons = ["1url.jpg", "2url.jpg", "3url.jpg", "4url.jpg", "5url.jpg", "6url.jpg"];

for (var i = 0; i < 14; i++) {
  console.log(blogIcons[i % blogIcons.length]);
}

When doing i % blogIcons.length you will get a number between 0 and blogIcons.length

Upvotes: 0

mpm
mpm

Reputation: 20155

What you are looking for is called modulo, the rest of the euclidian division of 2 numbers.

var blogIcons = ["1url.jpg", "2url.jpg", "3url.jpg", "4url.jpg", "5url.jpg", "6url.jpg"];
var imageCount = 10;
// the number of images that should be inserted.
for (var i = 0; i < imageCount; i++) {
  console.log(blogIcons[i % blogIcons.length])
}

I simplified your problem so it can run on StackOverflow. but you'll get the proper index by using "%"

So your script should look like that:

var blogIcons = ["1url.jpg", "2url.jpg", "3url.jpg", "4url.jpg", "5url.jpg", "6url.jpg"];
var blogFeedHeight = $(".blog-feed").height();
var imageDistance = 400; 
// Determining how many images to place based on the blog feed height;
var imageCount = Math.ceil(blogFeedHeight/imageDistance); 
// the number of images that should be inserted.
for(var i = 0; i < imageCount; i++){
    $('blog-feed').append('<div class="blog-icon">' + blogIcons[i % blogIcons.length] +'</div>')
}

Upvotes: 4

Related Questions