I have an array like this:
(我有一个像这样的数组:)
var arr1 = ["a", "b", "c", "d"];
How can I randomize / shuffle it?
(如何随机/随机播放?)
The de-facto unbiased shuffle algorithm is the Fisher-Yates (aka Knuth) Shuffle.
(实际无偏混洗算法是Fisher-Yates(aka Knuth)混洗。)
See https://github.com/coolaj86/knuth-shuffle
(参见https://github.com/coolaj86/knuth-shuffle)
You can see a great visualization here (and the original post linked to this )
(您可以在此处看到出色的可视化效果 (以及与此链接相关的原始文章))
function shuffle(array) { var currentIndex = array.length, temporaryValue, randomIndex; // While there remain elements to shuffle... while (0 !== currentIndex) { // Pick a remaining element... randomIndex = Math.floor(Math.random() * currentIndex); currentIndex -= 1; // And swap it with the current element. temporaryValue = array[currentIndex]; array[currentIndex] = array[randomIndex]; array[randomIndex] = temporaryValue; } return array; } // Used like so var arr = [2, 11, 37, 42]; arr = shuffle(arr); console.log(arr);
Some more info about the algorithm used.
(有关使用的算法的更多信息。)
1.4m articles
1.4m replys
5 comments
57.0k users