如何在JavaScript中对string中的字符进行混洗?

特别是,我想确保避免在Microsoft的浏览器select洗牌代码中犯的错误。 也就是说,我想确保每个字母在每个可能的位置都有相同的可能性。

例如给定“ABCDEFG”,返回类似“GEFBDCA”的内容。

我修改了一个来自Wikipedia上的Fisher-Yates Shuffle条目的例子来洗牌string:

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的答案中find。 使用JavaScript Array.sort()方法进行混洗是否正确? 。

如果“真正”的随机性很重要,我build议不要这样做。 看到我下面的编辑。

我只是想添加我最喜欢的方法为一个小品种;)

给定一个string:

 var str = "My bologna has a first name, it's OSCA R."; 

随机播放:

 var shuffled = str.split('').sort(function(){return 0.5-Math.random()}).join(''); 

输出:

 oa, a si'rSRn f gbomi. aylt AtCnhO ass eM as'oh ngS li Ays.rC nRamsb Oo ait a ,eMtf y alCOSf e gAointsorasmn bR Ms .' ta ih,a 

编辑:正如@PleaseStand指出,这并不符合OP的问题,因为它确实遭受“微软浏览器select洗牌”代码。 这不是一个很好的随机数发生器,如果你的string需要接近随机。 然而,它很快就让你的琴弦“混淆”,真正的随机性是无关紧要的。

他在下面链接的文章是一个很好的阅读,但解释了一个完全不同的用例,它影响统计数据。 我个人无法想象在string上使用这个“随机”function的实际问题,但作为一个编码器,你有责任知道什么时候使用这个。

我已经把这里留给了那里的所有随机随机器。

即使这已经得到解答,我想分享我提出的解决scheme:

 function shuffelWord (word){ var shuffledWord = ''; word = word.split(''); while (word.length > 0) { shuffledWord += word.splice(word.length * Math.random() << 0, 1); } return shuffledWord; } // 'Batman' => 'aBmnta' 

你也可以试试(jsfiddle) 。

 String.prototype.shuffle=function(){ var that=this.split(""); var len = that.length,t,i while(len){ i=Math.random()*len-- |0; t=that[len],that[len]=that[i],that[i]=t; } return that.join(""); } 
  shuffleString = function(strInput){ var inpArr = strInput.split("");//this will give array of input string var arrRand = []; //this will give shuffled array var arrTempInd = []; // to store shuffled indexes var max = inpArr.length; var min = 0; var tempInd; var i =0 ; do{ tempInd = Math.floor(Math.random() * (max - min));//to generate random index between range if(arrTempInd.indexOf(tempInd)<0){ //to check if index is already available in array to avoid repeatation arrRand[i] = inpArr[tempInd]; // to push character at random index arrTempInd.push(tempInd); //to push random indexes i++; } } while(arrTempInd.length < max){ // to check if random array lenght is equal to input string lenght return arrRand.join("").toString(); // this will return shuffled string } }; 

只要传递string函数,并返回洗牌string

 String.prototype.shuffle = function(){ return this.split('').sort(function(a,b){ return (7 - (Math.random()+'')[5]); }).join(''); };