2

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?

1 Answer 1

6

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.

Sign up to request clarification or add additional context in comments.

8 Comments

You can also remove append from loop.
If i = 0 would i % adList.length not result in NaN ?
@GabyakaG.Petrioli: Ah yes, I got it the wrong way around i % 0 would be NaN. Sorry about that, my bad.
@FrançoisWahl i % 0 would be dividing by zero... obviously this results in NaN.
@Steve Modulus is the remainder of a division operation. By definition, this means that the return value is limited to values between 0 and the denominator (never equaling the denominator).
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.