如何使用 jQuery.inArray 方法选择一组唯一的随机数(无重复)?

发布于 2024-10-19 17:17:26 字数 994 浏览 2 评论 0原文

这是一个 Javascript / jQuery 问题:

我尝试使用 jQuery.inArray 方法生成 1 到 21 之间的六个唯一随机数(无重复)。然后,这六个数字将用于从名为 logo1.jpg 到 logo21.jpg 的组中选择六个 .jpg 文件。

谁能告诉我我在这里做错了什么?

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

提前致谢...

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

苍白女子 2024-10-26 17:17:26

你有一些问题:

  • 全局窗口作用域中的变量

  • new关键字而不是文字声明的数组

    >

  • 在声明变量之前尝试使用变量

  • jQuery.inArray 被错误使用 ( inArray 返回一个数字,而不是 truefalse< /code>)

  • 带有 while 循环的低效代码,理论上可能会导致无限循环

,第二个与第三个相结合是这里的主要问题,因为第一次在数组中测试 x它是未定义(您仅使用var语句在if内定义它,因此x首先是未定义的),因此它匹配数组中的第一个元素(当您使用 new Array(6) 声明 r 时,它是 undefined),并且 inArray 函数返回 1,这导致无限循环。

您可以采取多种措施来修补该代码,但我认为使用不同的方法完全重写可能会更好,并且根本不需要 jQuery。

您的代码的修改版本应该可以正常工作:

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);
}

解释一下我在这里所做的事情:

  • 用您拥有的所有可能值(数字1到21)初始化一个数组

  • 仅运行与您要选择的数字相同的循环次数。

  • 生成一个从 0 到数字数组中可用的最大索引的随机数

  • 使用以下命令从数组中删除该索引处的数字splice,然后使用它为innerHTML调用创建字符串(splice 返回从数组中删除的元素作为另一个新数组)。

  • 此外,logosElement 变量在开始时会被缓存,因此您只需对该元素执行一次 DOM 查找。

有更多方法可以重写甚至清理代码,但我认为这将是帮助您解决问题的最干净的方法(并且它是跨浏览器安全的!不需要添加 jQuery,除非您需要它来实现其他功能)

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 combined 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 complete 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)

烟花肆意 2024-10-26 17:17:26

除了 while 循环后面的额外右括号之外,它不起作用的最明显原因是对 $.inArray 方法如何工作的轻微误解。 $.inArray 返回数组中匹配值的第一个索引,如果未找到,则返回 -1-1 是一个“真实”值,这意味着如果随机数不在数组中,您的 while 循环将继续执行。事实上,它会继续执行,直到找到数组第 0 个位置的数字。

为了解决该特定问题,您需要检查它是否大于 -1,以及在循环之前将 x var 设置为随机数:

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

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

在评论回复您的问题时,Pointy还提到了 Fisher-Yates Shuffle。这种改组方法可能会比您正在使用的方法提供更好的分布。

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

俏︾媚 2024-10-26 17:17:26
// 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;
// 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;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文