从数组中获取随机数,不重复(使用Timer:)

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了从数组中获取随机数,不重复(使用Timer:)相关的知识,希望对你有一定的参考价值。

[嗨,谢谢您阅读这篇文章。

我正在尝试创建一个自动的宾果游戏大声号码游戏,但在控制台日志上却一直未定义。有什么想法吗?

我有一个数组,需要无重复地随机调用这些项目,当结束时停止并说“结束”或“结束”之类的东西。

非常感谢!!!

  var nums = ["one","two","three","four","five","six","seven","eight","nine","ten"],
ranNums = [],
i = nums.length,
j = 0;

      setInterval(getNum,2000);

      function getNum(){
       j = Math.floor(Math.random() * (i+1));
ranNums.push(nums[j]);
nums.splice(j,1);
          console.log(ranNums[ranNums.length-1]);
          }
答案

问题是,在对数组进行拼接后,您不会修改'i'变量。

例如,您的数组最终可能成为

nums = ["one","two","three","four","ten"]

虽然您的'i'仍为10,所以'j'可能获得的值对于您的数组而言过大,从而导致您无法定义。

要解决此问题,请在函数末尾使'i'获得新的数组长度或将其减小1

另一答案

您的代码似乎还不错,只需要在弹出每个元素时更新nums长度即可。这是一种方法。

var nums = ["one","two","three","four","five","six","seven","eight","nine","ten"],
ranNums = [],
i = nums.length,
j = 0;

setInterval(getNum,2000);

function getNum(){
  i=nums.length
  if(i!=0){
    j = Math.floor(Math.random() * (i));
    ranNums.push(nums[j]);
    nums.splice(j,1);
    console.log(ranNums[ranNums.length-1]);
  }else{
    alert('The end');
  }
}
另一答案

例如,您可以使用while操作数:

    var nums = ["one","two","three","four","five","six","seven","eight","nine","ten"];
    var usedNums = [];
    while (nums.length) {
      var randomIndex = Math.floor(Math.random() * (nums.length - 1));
      var randomNumber = nums.splice(randomIndex, 1)[0];
      console.log('number ' + randomNumber.toString());
      usedNums.push(randomNumber);
    };
    console.log('nums end');
另一答案

这里有两个错误。您未在此处重设i的值。同样是Math.random * i而不是i+1

请参见下面的代码以供参考

var nums = ["one","two","three","four","five","six","seven","eight","nine","ten"],
ranNums = [],
i = nums.length,
j = 0;

setInterval(getNum,2000);

function getNum() {
    j = Math.floor(Math.random() * (i));
    // console.log(j);  
    ranNums.push(nums[j]);
    nums.splice(j,1);
    i = nums.length;
    let newValue = ranNums[ranNums.length-1];
    if (!newValue) {
        newValue = "The end!!"
    }
    console.log(newValue);
}
另一答案

希望对您有帮助:)

var nums = ["one","two","three","four","five","six","seven","eight","nine","ten"],
ranNums = [],
j = 0;

intervall = setInterval(getNum,2000);
  function getNum(){
  
    i = nums.length
    
    if(i == 0) {
      clearInterval(intervall)
      console.log('the end')
    } else {
        console.log(i)
        j = Math.floor(Math.random() * (i));
        ranNums.push(nums[j]);
        nums.splice(j,1);
        console.log(ranNums[ranNums.length-1]);
      }
   }

以上是关于从数组中获取随机数,不重复(使用Timer:)的主要内容,如果未能解决你的问题,请参考以下文章

如何从字符串数组中获取随机字符串 [重复]

js从数组中取出n个不重复的数据

如何从数组中获取随机元素[重复]

JS生成不重复的随机数组的简单实例

如何从node.js中的二维数组中获取随机项[重复]

JavaScript随机获取数组值不重复Mathfloorrandompush