不要重复 math.random 中的任何项目

don't repeat any items from math.random

本文关键字:任何 项目 random math      更新时间:2023-09-26

我正在使用它从我的数组中获取一个随机项目(并将其附加到每个列表项)

   $('li').each(function(){
       var items = Array('the','and','to','a');
       var item = items[Math.floor(Math.random()*items.length)];
       $(this).append(item);
    });

我敢肯定这是一件很快的事情,但我真的不知道去哪里看。如何确保没有重复项目?

在这里工作演示

您需要从数组中删除已使用的值。

  var items = Array('the', 'and', 'to', 'a');
  $('li').each(function () {
      var randomNum = Math.floor(Math.random() * items.length)
      var item = items[randomNum];
      $(this).append(item);
      items.splice(randomNum, 1);
      
  });

Se 你的演示在 JsFiddle 上

尝试

var items = new Array('the','and','to','a');
$('li').each(function(){
    var item = items.splice(Math.floor(Math.random() * items.length), 1);
    $(this).append(item);
});

演示:小提琴

所以你想让元素随机但不重复?然后,您要查找的是随机排列。如果你想要一个快速的解决方案,只需随机交换数组中的元素。如果你想要一个均匀分布的随机排列,看看Eric Lippert关于这个主题的文章:http://ericlippert.com/2013/05/02/producing-permutations-part-six/