Use Fisher-Yates 洗牌算法的现代版本 https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle#The_modern_algorithm:
/**
* Shuffles array in place.
* @param {Array} a items An array containing the items.
*/
function shuffle(a) {
var j, x, i;
for (i = a.length - 1; i > 0; i--) {
j = Math.floor(Math.random() * (i + 1));
x = a[i];
a[i] = a[j];
a[j] = x;
}
return a;
}
ES2015(ES6)版本
/**
* Shuffles array in place. ES6 version
* @param {Array} a items An array containing the items.
*/
function shuffle(a) {
for (let i = a.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[a[i], a[j]] = [a[j], a[i]];
}
return a;
}
但请注意,交换变量解构赋值 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#Swapping_variables截至 2017 年 10 月,导致显着的性能损失。
Use
var myArray = ['1','2','3','4','5','6','7','8','9'];
shuffle(myArray);
实施原型
Using Object.defineProperty
(取自此 SO 答案的方法 https://stackoverflow.com/a/30391923/1256925)我们还可以将此函数实现为数组的原型方法,而无需让它出现在循环中,例如for (i in arr)
。以下将允许您致电arr.shuffle()
打乱数组arr
:
Object.defineProperty(Array.prototype, 'shuffle', {
value: 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;
}
});