Last active
April 22, 2022 09:01
-
-
Save DefectingCat/6184d3109be70dd5c51f27d3b56540b2 to your computer and use it in GitHub Desktop.
利用类似洗牌的方式随机打乱数组
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
let arr = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']; | |
function shuffle(arr) { | |
let cac; | |
let len = arr.length - 1; | |
let ran; | |
for (let i = 0; i < len; i++) { | |
// 保存当前位 | |
cac = arr[i]; | |
// 剩下位的随机抽取 | |
ran = Math.floor(Math.random() * (len - i + 1) + i); | |
// 将随机抽取的位与当前位替换 | |
arr[i] = arr[ran]; | |
arr[ran] = cac; | |
} | |
} | |
shuffle(arr); | |
console.log(arr.length); | |
// arr.sort(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment