使用javascript生成唯一的随机数

Din*_*ani 0 javascript jquery html5

我使用以下代码生成从0到15的随机数.我使用函数random()生成唯一的数字我调用这样的函数

cat=random();
Run Code Online (Sandbox Code Playgroud)

我将随机数保存在数组r []中.并检查新生成的数字是否在数组中.如果发生重复,我再次调用random()函数.我使用警报只是检查它是否正常工作

function random(){
    var ran,max=0,min=0;
    max=r.length;
    alert(max);
    if (max>15)
        alert("no more space");
    ran=Math.floor(Math.random() * 15) + 0;
    for (i=0;i<max;i++)
    if (ran==r[i])
        min++;
    if (min>0){
        alert("calling");
        random();  //return in here
    }else{
        i=parseInt(max);
        r[i]=ran;   
        return(ran);
        alert(ran); 
    }                   
}
Run Code Online (Sandbox Code Playgroud)

但是当复制发生时函数内的变量返回可以有人帮助解决这个问题.

Tim*_*own 5

我创建了一个数组并使用Fisher-Yates对其进行洗牌.

function shuffle(arr) {
    var shuffled = arr.slice(0), i = arr.length, temp, index;
    while (i--) {
        index = Math.floor(i * Math.random());
        temp = shuffled[index];
        shuffled[index] = shuffled[i];
        shuffled[i] = temp;
    }
    return shuffled;
}

// Create the array
var i = 16, arr = [];
while (i--) arr[i] = i;

// Shuffle it
arr = shuffle(arr);

// Array is now the numbers 0-15 in a random order
console.log(arr);
Run Code Online (Sandbox Code Playgroud)