Ans*_*hul 447 javascript
可能重复:
如何随机化一个javascript数组?
我想在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]
Run Code Online (Sandbox Code Playgroud)
Jef*_*eff 904
使用现代版本的Fisher-Yates shuffle算法:
/**
* 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;
}
Run Code Online (Sandbox Code Playgroud)
/**
* 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;
}
Run Code Online (Sandbox Code Playgroud)
但请注意,截至2017年10月,使用解构分配交换变量会导致重大的性能损失.
var myArray = ['1','2','3','4','5','6','7','8','9'];
shuffle(myArray);
Run Code Online (Sandbox Code Playgroud)
Ble*_*der 461
您可以使用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;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
390087 次 |
| 最近记录: |