1 var arr = [1,2,3,4,5,6,7,8,9,10]; 2 3 function randSort1(arr){ 4 for(var i = 0,len = arr.length;i < len; i++ ){ 5 var rand = parseInt(Math.random()*len); 6 var temp = arr[rand]; 7 arr[rand] = arr[i]; 8 arr[i] = temp; 9 } 10 return arr; 11 } 12 13 console.log(randSort1(arr));
方法二
var arr = [1,2,3,4,5,6,7,8,9,10]; function randSort2(arr){ var mixedArray = []; while(arr.length > 0){ var randomIndex = parseInt(Math.random()*arr.length); mixedArray.push(arr[randomIndex]); arr.splice(randomIndex, 1); } return mixedArray; } console.log(randSort2(arr));
方法三
var arr = [1,2,3,4,5,6,7,8,9,10]; arr.sort(function(){ return Math.random() - 0.5; }) console.log(arr);
以上代码是我收集的,并非原创