Created
April 14, 2021 16:12
-
-
Save zhongyangxun/c62a71e17ce5c0eff02db0ada3329daf 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
function shuffle(arr) { | |
if (!arr || arr.length === 0) { | |
return []; | |
} | |
if (arr.length === 1) { | |
return [...arr]; | |
} | |
const map = new Map(); | |
const newArr = [...arr]; | |
for (let i = 0; i < newArr.length; i++) { | |
if (map.has(i)) { | |
continue; | |
} | |
const index = Math.floor(Math.random() * arr.length); | |
if (index !== i) { | |
const temp = newArr[i]; | |
newArr[i] = newArr[index]; | |
newArr[index] = temp; | |
map.set(i, 1); | |
map.set(index, 1); | |
} | |
} | |
return newArr; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment