[Javascript]隨機排序陣列
發表於 : 2012年 3月 15日, 14:50
隨機產生亂數是可以利用 Math.random() 來產生, 不過若是需求是像抽獎這樣的應用, 已有一群號碼, 而要隨機抽出又不重覆的狀況下, 利用隨機排序陣列是比較簡單快速的作法.
如何隨機排序陣列, 可以利用這篇文章的 shuffle 函數: http://javascript.about.com/library/blsort4.htm
利用隨機交換的方式, 將陣列排出結果, 程式碼如下:
如何隨機排序陣列, 可以利用這篇文章的 shuffle 函數: http://javascript.about.com/library/blsort4.htm
利用隨機交換的方式, 將陣列排出結果, 程式碼如下:
代碼: 選擇全部
Array.prototype.shuffle = function() {
var s = [];
while (this.length) s.push(this.splice(Math.random() * this.length, 1));
while (s.length) this.push(s.pop());
return this;
}