JS陣列隨機排序的三種方法

weixin_33924312發表於2017-08-17

方法一:

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));
1281633-5fa1c4ced6453417.png
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));
1281633-883bddf39d8740f8.png
image.png

方法三:

var arr = [1,2,3,4,5];
arr.sort(function(){
  return Math.random()-0.5;
})
console.log(arr);
1281633-97aeed091f93e9de.png
image.png

相關文章