我有一个 javascript 数组,我想根据我指定的数字或字符串对其进行排序。我希望数组看起来是随机排序的,但如果输入是“6543”,数组将始终按相同顺序排序。
最佳答案
Javascript 本身不提供此功能——它的 RNG 不能被播种。人们仍然可以采取不同的方法。这是一个。种子必须大于一(否则将返回相同的数组),并且应该大于数组大小以获得足够的“随机性”。
Array.prototype.deterministicShuffle=function(seed){
// A little error handling, whynot!
if(!seed)
throw new Error("deterministicShuffle: seed not given, or 0");
var temp,j;
for(var i=0; i<this.length; i++){
// Select a "random" position.
j = (seed % (i+1) + i) % this.length;
// Swap the current element with the "random" one.
temp=this[i];
this[i]=this[j];
this[j]=temp;
}
return this;
}
// Try it out, Aaron!
alert([0,1,2,3,4,5,6,7,8,9].deterministicShuffle(6543));
alert([0,1,2,3,4,5,6,7,8,9].deterministicShuffle(6544));
alert([0,1,2,3,4,5,6,7,8,9].deterministicShuffle(6545));
关于Javascript:根据输入数字对数组进行排序。应该随机排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5371452/