<script>
  var a = [1,2,3,4,5];
  var newa = [];
  function zz(){
    for(var i=0; len=a.length; i++){
      var j = Math.floor(Math.random()*a.length);
      newa[i]=a[j];
      a.splice(j, 1);
    }
    console.log(newa);
  }
  zz();
</script>

  注:a 是需要重排的数组。

 

在维基百科Fisher-Yates shuffle提到了一种方式:

将数组倒序循环取得随机位置来做位置交换

<script>
   var a = [1,2,3,4,5];
   function zz(){
       for(var i=a.length-1; i>=0; i--){
      var j = Math.floor(Math.random()*a.length);
      var newa = a[i];
      a[i] = a[j];
      a[j] = newa;
       }
       console.log(a);
   }
   zz();
</script>

  

相关文章:

  • 2021-12-21
  • 2021-10-30
  • 2022-12-23
  • 2022-12-23
  • 2022-01-01
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2021-12-11
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案