有数组:
var arr1 = ["a", "b", "c", "d"];
怎样才能变得random?
<script type="text/javascript">
//随机取得数组中的一个
var Arr = ["a","b","c","d"];
var n = Math.floor(Math.random() * Arr.length + 1)-1;
alert(Arr[n]);
</script>
提供个思路:可以在0-3生成四次随机数,然后将这四个随机数分别作为arr1的索引取得arr1中的值,再拼成数组
循环数组,取得每成员,根据该成员作为handcode,生成随机数
事实上的无偏移Shuffle算法是 Fisher-Yates (又名 Knuth)Shuffle
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 sovar arr = [2, 11, 37, 42];
arr = shuffle(arr);
console.log(arr);
下面是计算机优化版本的 Fisher-Yates 的 Durstenfeld shuffle 的 JavaScript 执行:
/**
* Randomize array element order in-place.
* Using Durstenfeld shuffle algorithm.
*/function shuffleArray(array) {
for (var i = array.length - 1; i > 0; i--) {
var j = Math.floor(Math.random() * (i + 1));
var temp = array[i];
array[i] = array[j];
array[j] = temp;
}}
Fisher-yates 算法的工作原理是为每个原始数组元素选择一个随机元素,然后将其排除之外。就像从一副扑克牌中随机抽取一样。
这种排除是通过一种聪明的方式实现的(由 Durstenfeld 为计算机使用而发明) ,即将选中的元素与当前元素交换,然后从余下的元素中选择下一个随机元素。为了获得最佳效率,循环向后运行以简化随机选择(它始终可以从0开始) ,并跳过最后一个元素,因为没有其他选择了。
该算法的运行时间为O(n)。 请注意,洗牌是就地完成的。 因此,如果您不想修改原始数组,请使用 .slice(0)。
更新至 ES6 / ECMAScript 2015
新的 ES6允许我们一次分配两个变量。 当我们想要交换两个变量的值时,这尤其方便,因为我们可以在一行代码中这样做。下面是使用这个特性的同一函数的一个简短形式。
function shuffleArray(array) {
for (let i = array.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[array[i], array[j]] = [array[j], array[i]];
}}
我们可以(或者应该)使用它作为 Array 的一个原型:
Array.prototype.shuffle = function() {
var i = this.length, j, temp;
if ( i == 0 ) return this;
while ( --i ) {
j = Math.floor( Math.random() * ( i + 1 ) );
temp = this[i];
this[i] = this[j];
this[j] = temp;
}
return this;}