我:如何獲得一個獨特的隨機整數在一定範圍內的每個數字在該範圍內的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