首页 > 编程语言 > 详细

如何随机洗牌一个数组

时间:2017-08-21 12:20:45      阅读:243      评论:0      收藏:0      [点我收藏+]

在使用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

如何随机洗牌一个数组

原文:http://www.cnblogs.com/tgxh/p/7403639.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!