JS achieve a random array sort

 1     // 方法1
 2     function method1(arr){
 3         for(var i=0,len=arr.length;i<len;i++){
 4             var a=parseInt(Math.random()*len);
 5             var temp=arr[a];
 6             arr[a]=arr[i];
 7             arr[i]=temp;
 8         }
 9         return arr;
10     }
11     // 方法2
12     function method2(arr){
13         var newarr=[];
14         the while (arr.length> 0 ) {
 15              var len = the parseInt (Math.random () * arr.length);
 16              newarr.push (ARR [len]);
 . 17              arr.splice (len,. 1)   // splice ( index, num, x, x) function, index remove elements of position (must), the number num deleted (must), x element of the array to the new added (optional). This function returns a new array of elements to be deleted, while the original array is also changed; 
18 is          }
 . 19          return newarr;
 20 is      }
 21 is      // method. 3 
22 is      function the method3 (ARR) {
 23 is          arr.sort ( function () {
 24              return the Math .random () - 0.5 ;
 25          });
26         console.log(arr);
27     }

 

Guess you like

Origin www.cnblogs.com/dreamttt/p/12018927.html