更新時間:2021年12月22日13時42分 來源:傳智教育 瀏覽次數(shù):
<script> var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; function randSort1(arr) { for (var i = 0, len = arr.length; i < len; i++) { var rand = parseInt(Math.random() * len); var temp = arr[rand]; arr[rand] = arr[i]; arr[i] = temp; } return arr; } console.log(randSort1(arr)); </script>
<script> 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)); </script>
<script> var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; arr.sort(function () { return Math.random() - 0.5; }) console.log(arr); </script>
猜你喜歡: