This is a Javascript / jQuery question:
I’m trying to generate six unique random numbers between 1 and 21 (no duplicates), using the jQuery.inArray method. Those six numbers will then be used to select six .jpg files from a group named logo1.jpg through logo21.jpg.
Can anyone tell me what I’m doing wrong here?
<div id="client-logos"></div>
<script src="http://code.jquery.com/jquery-1.5.js"></script>
<script type="text/javascript">
Show = 6; // Number of logos to show
TotalLogos = 21; // Total number of logos to choose from
FirstPart = '<img src="/wp-content/client-logos/logo';
LastPart = '.jpg" height="60" width="120" />';
r = new Array(Show); // Random number array
var t=0;
for (t=0;t<Show;t++)
{
while ( jQuery.inArray(x,r)
{
var x = Math.ceil(Math.random() * TotalLogos);
});
r[t] = x;
var content = document.getElementById('client-logos').innerHTML;
document.getElementById('client-logos').innerHTML = content + FirstPart + r[t] + LastPart;
}
</script>
Thanks in advance…
you have a few issues there:
variables in the global window scope
an array declared with the
newkeyword instead of a literaltrying to use variables before declaring them
jQuery.inArray being incorrectly used (inArray returns a number, not
trueorfalse)inefficient code with a
whileloop which theoretically could lead to an infinite loopnow, the second combined with the third is the main issue here, as the first time you test for
xin the array it isundefined(you are only defining it inside theifwith avarstatement, so the x is at first undefined) and thus it matches the first element in the array (which isundefinedas you declaredrwithnew Array(6)) and the inArray function returns 1, which leads to an infinite loop.There are several things you could do to patch that code, but I think a complete rewrite with a different approach might be better and requires no jQuery at all.
This modified version of your code should work fine:
To explain a little what I did here:
initialize an array with all the possible values you have (numbers 1 to 21)
run a loop only as many times as numbers you want to pick.
generate a random number from 0 to the maximum index available in your numbers array
remove the number at that index from the array using splice, and then use it to create the string for the innerHTML call (splice returns the elements removed from the array as another new array).
additionally, the
logosElementvariable is cached at the beginning so you only do a single DOM lookup for the element.There are more ways that code can be rewritten and even cleaned up, but I figured this would be the cleanest way to help you with your issue (and it’s cross-browser safe! no need to add jQuery unless you need it for another functionality)