我试图在1-5,1-10,1-20等之间生成非重复的随机数。我正在使用Fisher-Yates Shuffle,但我不确定我是否在最好的方法。我的计划是将每个随机数与预定的变量名相关联。我想确保语法对于将随机值分配给预定变量名称是正确的。我是JavaScript新手,非常感谢任何见解。这是我的第一次演绎:
function shuffle(array) {
var i = array.length,
j = 0,
temp;
while (i--) {
j = Math.floor(Math.random() * (i+1));
temp = array[i];
array[i] = array[j];
array[j] = temp;
}
return array;
}
var ranNums = shuffle([1,2,3,4,5]);
var ranNum1 = ranNums.value;
var ranNum2 = ranNums.value;
var ranNum3 = ranNums.value;
var ranNum4 = ranNums.value;
var ranNum5 = ranNums.value;
答案 0 :(得分:0)
尝试使用以下代码FIDDLE:
var ranNum1 = ranNums[0];
var ranNum2 = ranNums[1];
var ranNum3 = ranNums[2];
var ranNum4 = ranNums[3];
var ranNum5 = ranNums[4];