Steve
Steve

Reputation: 14912

Repeating items in an array multiple times in a loop?

I have an array with 6 strings representing HTML image tags. I have some code which determines an amount of space to fill with these images.

I am using a loop, which works fine to pull from these 6 images and use 1 or all 6. My issue comes when I need MORE than 6, which would mean go through the array again and again. I am unsure how to best construct this loop. Currently I have

for (var i = 0; i < numAds ; i++) {
            $('#primary').append(adList[i]);
        };

I tried adding if (i > adList.length) { i=0 } before the jquery statement but then I got stuck in a loop and crashed the browser.

What am I missing here?

Upvotes: 2

Views: 1135

Answers (1)

Gabriele Petrioli
Gabriele Petrioli

Reputation: 195982

Use

$('#primary').append(adList[i % adList.length]);

The % is the modulus operator


Make sure, though, that adList is not empty or that would cause the i % adList.length to return NaN and crash make the adList[i % adList.length] return undefined what whatever sideffects this might bring.

Upvotes: 6

Related Questions