admin管理员组

文章数量:1402844

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=".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...

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./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...

Share Improve this question edited Sep 9, 2013 at 13:00 hakre 198k55 gold badges449 silver badges855 bronze badges asked Feb 28, 2011 at 14:42 Shaun ScovilShaun Scovil 3,9875 gold badges45 silver badges59 bronze badges 6
  • 2 Are you sure that's right? It looks like a syntax error around that "while" loop to me - there's a missing close-paren ... – Pointy Commented Feb 28, 2011 at 14:47
  • Also, it looks like you update exactly the same element over and over again with each random image. Is that really what you want? – Pointy Commented Feb 28, 2011 at 14:48
  • @Pointy: he sets the innerHTML to the content variable before re-assigning. @Shaun: As an aside, it's generally bad practice to modify innerHTML inside a loop. Generate your HTML string in the loop, but don't assign it to the element until after the loop ends. – Andy E Commented Feb 28, 2011 at 14:59
  • @Andy E oh I see - well that will work but it's a bad idea for other reasons, as you note :-) – Pointy Commented Feb 28, 2011 at 15:02
  • 2 @Shaun a better way to do this is the Fisher-Yates (or Knuth) shuffle - there's a Wikipedia article on the topic that's pretty understandable. You'd build an array of numbers 1 to 21, shuffle it, then pick the first 6 from the list. – Pointy Commented Feb 28, 2011 at 15:04
 |  Show 1 more ment

3 Answers 3

Reset to default 5

you have a few issues there:

  • variables in the global window scope

  • an array declared with the new keyword instead of a literal

  • trying to use variables before declaring them

  • jQuery.inArray being incorrectly used (inArray returns a number, not true or false)

  • inefficient code with a while loop which theoretically could lead to an infinite loop

now, the second bined with the third is the main issue here, as the first time you test for x in the array it is undefined (you are only defining it inside the if with a var statement, so the x is at first undefined) and thus it matches the first element in the array (which is undefined as you declared r with new 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 plete rewrite with a different approach might be better and requires no jQuery at all.

This modified version of your code should work fine:

var 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" />',
    array = [], // array with all avaiilable numbers
    rnd, value, i,
    logosElement = document.getElementById('client-logos');

for (i = 0; i < TotalLogos; i++) { // arrays are zero based, for 21 elements you want to go from index 0 to 20.
  array[i] = i + 1;
}

for (i = 0; i < Show; i++) { // pick numbers
  rnd = Math.floor(Math.random() * array.length); 
  value = array.splice(rnd,1)[0]; // remove the selected number from the array and get it in another variable

  logosElement.innerHTML += (FirstPart + value + LastPart);
}


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 logosElement variable 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)

The immediately obvious reason it's not working, other than the extra closing parenthesis after your while loop, is a slight misunderstanding on how $.inArray method works. $.inArray returns the first index of a matched value in the array, or -1 if it's not found. -1 is a "truthy" value, meaning your while loop will continue execution if the random number isn't in the array. In fact, it will continue execution until it finds the number at the 0th location of the array.

In order to fix that particular problem, you need to check that it's greater than -1, as well as setting the x var to a random number before the loop:

var x = Math.ceil(Math.random() * TotalLogos);

while ($.inArray(x, r) > -1) {
    x = Math.ceil(Math.random() * TotalLogos);
}
r[t] = x;

In the ment replies to your question, Pointy also mentions the Fisher-Yates Shuffle. That method of shuffling might give you better distribution than the approach you're using.

// Initial number
var x = Math.ceil(Math.random() * TotalLogos);

// Keep searching until a unique number is found
while ($.inArray(x, r) > -1) {
    x = Math.ceil(Math.random() * TotalLogos);
}

// If it's unique, set it
r[t] = x;

本文标签: