如何在JavaScript中对字符串中的字符进行随机播放? [英] How do I shuffle the characters in a string in JavaScript?
问题描述
特别是,我想确保避免在Microsoft的Browser Choice shuffle代码中犯下的错误。也就是说,我想确保每个字母在每个可能的位置都有相同的概率。
In particular, I want to make sure to avoid the mistake made in Microsoft's Browser Choice shuffle code. That is, I want to make sure that each letter has an equal probability of ending up in each possible position.
例如。鉴于ABCDEFG,返回类似GEFBDCA的内容。
e.g. Given "ABCDEFG", return something like "GEFBDCA".
推荐答案
我修改了维基百科上的Fisher-Yates Shuffle条目改组字符串:
String.prototype.shuffle = function () {
var a = this.split(""),
n = a.length;
for(var i = n - 1; i > 0; i--) {
var j = Math.floor(Math.random() * (i + 1));
var tmp = a[i];
a[i] = a[j];
a[j] = tmp;
}
return a.join("");
}
console.log("the quick brown fox jumps over the lazy dog".shuffle());
//-> "veolrm hth ke opynug tusbxq ocrad ofeizwj"
console.log("the quick brown fox jumps over the lazy dog".shuffle());
//-> "o dt hutpe u iqrxj yaenbwoolhsvmkcger ozf "
更多信息可在 Jon Skeet对 https://stackoverflow.com/questions/962802/is-it-correct-to-use-javascript-array-sort-method-for-shuffling\">使用JavaScript Array.sort()方法进行改组是正确的?。
More information can be found in Jon Skeet's answer to Is it correct to use JavaScript Array.sort() method for shuffling?.
这篇关于如何在JavaScript中对字符串中的字符进行随机播放?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!