javascript 在javascript中生成范围内的随机数而不重复数字

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13902365/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 20:06:36  来源:igfitidea点击:

Generate random number within range without repeating numbers in javascript

javascript

提问by Skizo

Possible Duplicate:
Generate 8 unique random numbers between 1 and 100
Generate unique number within range (0 - X), keeping a history to prevent duplicates

可能的重复:
生成 1 到 100 之间的 8 个唯一随机
数在范围 (0 - X) 内生成唯一编号,保留历史记录以防止重复

I need loop that will run 80 times and generate random number between 0-79 but it will not repeat number that has been generated already.
How can I do that?

我需要循环运行 80 次并生成 0-79 之间的随机数,但它不会重复已经生成的数字。
我怎样才能做到这一点?

回答by closure

  for (var i = 0, ar = []; i < 80; i++) {
    ar[i] = i;
  }

  // randomize the array
  ar.sort(function () {
      return Math.random() - 0.5;
  });

// You have array ar with numbers 0 to 79 randomized. Verify
console.log(ar);

// 您有一个随机数为 0 到 79 的数组 ar。核实
console.log(ar);

// take out elements like this
ar.pop()

// 取出这样的元素
ar.pop()