方法一:
var arr = [1,2,3,4,5];
function randSort(arr){
for(let i = 0,len = arr.length; i < len;i++){
let rand = parseInt(Math.random() * len);
let temp = arr[rand];
arr[rand] = arr[i];
arr[i] = temp;
}
return arr;
}
console.log(randSort(arr));
image.png
方法二:
var arr = [1,2,3,4,5];
function randSort(arr){
let mixedArr = [];
while(arr.length > 0){
let randomIndex = parseInt(Math.random()*arr.length);
mixedArr.push(arr[randomIndex]);
arr.splice(randomIndex,1);
}
return mixedArr;
}
console.log(randSort(arr));
image.png
方法三:
var arr = [1,2,3,4,5];
arr.sort(function(){
return Math.random()-0.5;
})
console.log(arr);
image.png
网友评论