如何使用fisher yate shuffle方法生成唯一數組項?我發現下面的代碼,但沒有奏效。隨機數組無重複失敗
function shuffle(array) {
var i = array.length,
j = 0,
temp;
while (i--) {
j = Math.floor(Math.random() * (i+1));
// swap randomly chosen element with current element
temp = array[i];
array[i] = array[j];
array[j] = temp;
}
return array;
}
var ranNums = shuffle([1,2,3,4,5,6,7,8,9,10]);
console.log(ranNums)
「無效」意味着什麼? – str
它工作正常... –