我有一个这样的数组:
var arr1 = ["a", "b", "c", "d"];
我怎样才能随机化/随机化它?
最佳答案
事实上的无偏洗牌算法是 Fisher-Yates (aka Knuth) Shuffle .
你可以看到一个great visualization here (和原帖linked to this)
function shuffle(array) {
let currentIndex = array.length, randomIndex;
// While there remain elements to shuffle.
while (currentIndex != 0) {
// Pick a remaining element.
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex--;
// And swap it with the current element.
[array[currentIndex], array[randomIndex]] = [
array[randomIndex], array[currentIndex]];
}
return array;
}
// Used like so
var arr = [2, 11, 37, 42];
shuffle(arr);
console.log(arr);
更多信息 about the algorithm用过。
关于javascript - 如何随机化(洗牌)JavaScript 数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56233249/