PHP 提供了 shuffle 函式,可以將陣列元素隨機打亂。JavaScript 本身沒有同名方法,但我們可以自己實作,甚至透過 prototype 擴充所有陣列。
var shuffle = function (v) {
for (var j, x, i = v.length; i; j = Math.floor(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];
console.log(shuffle(a));這個做法從陣列尾端開始,隨機挑選一個位置並交換元素,能在原陣列上完成隨機排序。
如果希望所有陣列都能直接呼叫 shuffle,可以擴充 Array 的 prototype。
if (!Array.prototype.shuffle) {
Array.prototype.shuffle = function () {
for (var j, x, i = this.length; i; j = Math.floor(Math.random() * i), x = this[--i], this[i] = this[j], this[j] = x);
return this;
};
}
var list = [1, 2, 3, 4, 5];
console.log(list.shuffle());這種寫法簡潔,也能讓陣列操作更直覺。不過在大型專案中,擴充原生 prototype 仍需小心命名衝突與維護問題。