PHP 有個很方便的 shuffle() 可以直接打亂陣列,JavaScript 卻沒有對應的內建方法。沒關係,自己擴充一個即可。
<script type="text/javascript">
// <![CDATA[
// 說明:為 Javascript 陣列 shuffle 方法
var shuffle = function(v){
for (var j, x, i = v.length; i; j = parseInt(Math.random() * i), x = v[--i], v[i] = v[j], v[j] = x);
return v;
};
var a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
document.write("A = ", a.join(","), "<br />shuffle(A) = ", shuffle(a));
// ]]>
</script>
輸出結果類似:
A = 0,1,2,3,4,5,6,7,8,9 shuffle(A) = 1,5,0,9,2,3,6,8,4,7
若希望像 PHP 那樣直接 a.shuffle() 呼叫,掛到原型上即可:
<script type="text/javascript">
// <![CDATA[
var a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
if (!Array.prototype.shuffle) {
Array.prototype.shuffle = function() {
for (var j, x, i = this.length; i; j = parseInt(Math.random() * i), x = this[--i], this[i] = this[j], this[j] = x);
return this;
};
}
document.write("A = ", a.join(","), "<br />A.shuffle() = ", a.shuffle());
// ]]>
</script>
for (var j, x, i = v.length; i; ...) 的三段依序是:
i。i 為 0 時是假值,迴圈結束。因為更新式在每次迭代結束時才執行,而 --i 位於其中,所以第一次迭代處理的是最後一個元素,最後一次處理索引 1 的元素。這正是 Fisher-Yates 洗牌演算法。
迴圈主體是空的(只有一個分號),所有工作都在更新式裡完成。語法完全合法,但可讀性極差。
Array.prototype.shuffle = function () {
for (let i = this.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[this[i], this[j]] = [this[j], this[i]];
}
return this;
};
用 if 包住是對的。檢查 Array.prototype.shuffle 是否已存在,可以避免與其他函式庫或未來的語言版本衝突。不過更好的做法是根本不擴充原型,直接匯出獨立函式:
export function shuffle(arr) {
const result = arr.slice(); // 不改動原陣列
for (let i = result.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[result[i], result[j]] = [result[j], result[i]];
}
return result;
}
原版會改動原陣列。範例中 a 被 shuffle 之後就不再保持原順序了。若後續邏輯還需要原始順序,記得先複製。
最後,document.write 只適合在頁面解析階段使用,若在 onload 後呼叫會清空整個頁面。範例中用它只是為了方便展示結果,正式程式請用 DOM API 輸出。