在Array中生成随机数而不重复 - JavaScript [英] Generating random number in Array without repeatition - JavaScript

查看:90
本文介绍了在Array中生成随机数而不重复 - JavaScript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我知道这个任务已经被问到了,但是所有给出的答案都已经被我知道了。我不想对所有可能的数字做一个变量(这总是答案)。所以要回答这个问题,我想制作一个随机数字生成器,它会生成7个数字,但不能相同。例如,我得到了随机数字:
5,16,12,5,21,37,2......但我不想让数字5再次使用,所以我需要不同的数字。我为这一代做了一个代码,但我想不出有什么好的方法来做到这一点。我在想,也许检查数字是否已经在数组中,如果是,然后生成另一个数字,但由于我是JavaScript业余爱好者,我不知道该怎么做。所以这里是我的JavaScript代码:

// JavaScript Document

 函数TableOn()
{
document.write(< table border ='1'>);

函数TableOff()
{
document.write(< / table>);


函数RandNum()
{
var n = new Array(); ((1+(Math.random()* 40)));
for(var i = 0; i <7; i ++)
{
n [i] = Math.round
}
TableOn();
for(var c = 0; c< 7; c = c + 1)
{
document.write(< tr>< td>+ n [c] + < / TD>< / TR> 中);
}
TableOff();
}

在HTML中,我只有一个按钮,即 onclick =RandNum() ...原谅我的英语。

它是这样的:

  var nums = [],numsLen = 5,maxNum = 100,num; (nums.length< numsLen){
num = Math.round(Math.random()* maxNum);
if(nums.indexOf(num)=== -1){
nums.push(num);




$ b $ p
$ b

这将生成一个数组,其中包含5个随机数0..100。
numsLen 不能大于 maxNum 。)


so I know this questing has been asked, but all the answers that were given are already known to me. I don't want to make a variable of all the posible numbers (that was always the answer). So to go to the question, I want to make a random number generator, that will generate me 7 numbers, that must not be the same. For example, I get random numbers: "5,16,12,5,21,37,2" ... But I don't want the number 5 to be used again, so I want different numbers. I made a code for the generation, but I can not think of any good method/way to do this. I was thinking that maybe check if the number is already in array and if it is, then generate another number, but as I'm amateur in JavaScript, I don't know how to do this. So here is my JavaScript code:

// JavaScript Document

function TableOn()
{
    document.write("<table border='1'>");
}
function TableOff()
{
    document.write("</table>");
}

function RandNum()
{
    var n = new Array();
    for(var i=0;i<7;i++)
    {
        n[i] = Math.round((1+(Math.random()*40)));
    }
    TableOn();
    for(var c=0;c<7;c=c+1)
    {
        document.write("<tr><td>"+n[c]+"</td></tr>");
    }
    TableOff();
}

In HTML I just have a button, that is onclick="RandNum()" ... Pardon for my English.

解决方案

I would do it like this:

var nums = [], numsLen = 5, maxNum = 100, num;
while (nums.length < numsLen) {
    num = Math.round(Math.random() * maxNum);
    if (nums.indexOf(num) === -1) {
        nums.push(num);
    }
}

This generates an array with 5 random numbers in the range 0..100. (numsLen cannot be greater than maxNum.)

这篇关于在Array中生成随机数而不重复 - JavaScript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆