Skip to content

Instantly share code, notes, and snippets.

@zhongyangxun
Created April 14, 2021 16:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zhongyangxun/c62a71e17ce5c0eff02db0ada3329daf to your computer and use it in GitHub Desktop.
Save zhongyangxun/c62a71e17ce5c0eff02db0ada3329daf to your computer and use it in GitHub Desktop.
数组乱序。
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