我:如何获得一个独特的随机整数在一定范围内的每个数字在该范围内的JavaScript?
function getRandomInt(min, max){
return Math.floor(Math.random() * (max - min + 1)) + min;
}
但问题是我想要随机化的东西与元素人口在数组(所以他们不会在我填充的东西,每次出现在相同的顺序),所以我需要以确保返回的号码与其他号码相比是唯一的。
所以不是:
for(var i = 0; i < myArray.length; i++) {
}
我:
var i;
var count = 0;
while(count < myArray.length){
count++;
i = getRandomInt(0, myArray.length); // TODO ensure value is unique
// do stuff with myArray[i];
}
你是对的!你可以包含代码,所以我可以标记为答案:function shuffle(array)var tmp,current,top = array.length; (top)while( - top){current_ Math.floor(Math.random()*(top + 1)); tmp = array [current]; array [current] = array [top]; array [top] = tmp; } return array; } – markmnl