我如何洗牌数组?

我想在JavaScript中洗牌一个元素数组,就像这样:

[0, 3, 3] -> [3, 0, 3]
[9, 3, 6, 0, 6] -> [0, 3, 6, 9, 6]
[3, 3, 6, 0, 6] -> [0, 3, 6, 3, 6]
519023 次浏览

使用# EYZ0:

/**
* 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;
}

但是请注意,从2017年10月开始,用解构的任务交换变量会导致显著的性能损失。

使用

var myArray = ['1','2','3','4','5','6','7','8','9'];
shuffle(myArray);

实现原型

使用Object.defineProperty (方法从这个SO答案),我们还可以将这个函数作为数组的原型方法来实现,而不需要在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;
}
});

你可以使用Fisher-Yates洗牌(代码改编自这个网站):

function shuffle(array) {
let counter = array.length;


// While there are elements in the array
while (counter > 0) {
// Pick a random index
let index = Math.floor(Math.random() * counter);


// Decrease counter by 1
counter--;


// And swap the last element with it
let temp = array[counter];
array[counter] = array[index];
array[index] = temp;
}


return array;
}