如何随机洗牌一个数组

在使用javascript的时候有可能会有随机打乱一个数组的需求,我们可以利用数组的sort方法和Math.random来随机排序

const arr = [1,2,3];

arr.sort(() => 0.5 - Math.random())

console.log(arr)

主要利用了Math.random()生成随机数与0.5的大小比较来排序,如果0.5 - Math.random()大于或等于0,数组中的两个数位置不变,小于0就交换位置。

乍一看这样是达到了随机排序的效果,但是实际上这个排序是不那么随机的。具体分析可以参考这篇文章

 

一个更好方式是采用Fisher–Yates shuffle算法,在此处的使用方式如下

const arr = [1,2,3,4,5,6]

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;
}
arr.shuffle()

https://stackoverflow.com/questions/2450954/how-to-randomize-shuffle-a-javascript-array

posted @ 2017-08-21 12:02  tgxh  阅读(365)  评论(0编辑  收藏  举报