更新时间:2021年12月22日13时42分 来源:传智教育 浏览次数:
<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>
猜你喜欢: