在循环中多次重复数组中的项?

时间:2022-12-19 20:21:48

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.

我有一个包含6个字符串的数组,它们表示HTML图像标签。我有一些代码来确定要填充这些图像的空间。

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

我正在使用一个循环,它可以很好地从这6个图像中提取,并使用1个或全部6个。当我需要大于6的时候,我的问题就来了,这意味着一次又一次地遍历数组。我不确定如何最好地构造这个循环。目前我有

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.

在jquery语句之前,我尝试添加if (i> adList.length) {I =0},但随后我陷入了一个循环,并使浏览器崩溃。

What am I missing here?

我错过了什么?

1 个解决方案

#1


5  

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.

但是要确保adList不是空的,否则会导致i % adList。返回NaN的长度和崩溃使adList成为[i % adList]。返回不确定的东西,无论它带来什么。

#1


5  

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.

但是要确保adList不是空的,否则会导致i % adList。返回NaN的长度和崩溃使adList成为[i % adList]。返回不确定的东西,无论它带来什么。