我试图将数字0-9变为随机顺序。 EX:2,4,0,1,3,5,9,7,8,6 ......目前它从1开始而不是0。 这就是我正在使用的 - (我对js的了解是min。)
<script type="text/javascript" language="Javascript">
function pick(n, min, max){
var values = [], i = max;
while(i >= min) values.push(i--);
var results = [];
var maxIndex = max;
for(i=1; i <= n; i++){
maxIndex--;
var index = Math.floor(maxIndex * Math.random());
results.push(values[index]);
values[index] = values[maxIndex];
}
return results;
}
function go(){
var running = true;
do{
if(!confirm(pick(10, 0, 9))){
running = false;
}
}while(running);
}
</script>
感谢您的投入......
答案 0 :(得分:3)
为了便于阅读和更容易调试,在这里创建更多功能可能更有用。
// Creates the array [min, min+1, ..., max-1, max]
function createRange(min, max) {
var range = [];
while (min <= max) {
range.push(min);
min++;
}
return range;
}
// Fisher-Yates Shuffle from http://bost.ocks.org/mike/shuffle/
// but you can replace this with your own shuffler if you want
function yatesShuffle(array) {
var m = array.length, t, i;
while (m) {
i = Math.floor(Math.random() * m--);
t = array[m];
array[m] = array[i];
array[i] = t;
}
return array;
}
// Pick `n` numbers from the range `[min, ..., max]`.
// `n` must be less than or equal to `(max - min)`.
function pick(n, min, max) {
var range = createRange(min, max);
var shuffled = yatesShuffle(range);
return shuffled.slice(0,n);
}
function go(){
var running = true;
do{
if(!confirm(pick(10, 0, 9))){
running = false;
}
}while(running);
}