如何打乱一个数组?
如何打乱一个数组?
这个问题已经有了答案:
我想像这样在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]
admin 更改状态以发布 2023年5月24日
你可以使用Fisher-Yates Shuffle(代码参考自这个网站):
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; }
/** * 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; } });