我有一个像这样的数组:
var arr1 = ["a", "b", "c", "d"];
我怎样才能随机/洗牌它?
事实上的无偏洗牌算法是Fisher-Yates(又名 Knuth)洗牌 https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle.
你可以看到一个这里有很棒的可视化 http://bost.ocks.org/mike/shuffle/(以及原来的帖子链接到此 http://sedition.com/perl/javascript-fy.html)
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);
更多信息关于算法 http://en.wikipedia.org/wiki/Fisher-Yates_shuffle used.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)