const shuffle = function (arr) {
return arr.sort((a, b) => Math.random() > 0.5);
}
第二种,获取到数据的所有 index,然后每次随机取一个
const shuffle = function (arr) {
let indexes = Array.from({length: arr.length}).map((_, i) => i);
return arr.map(_ => {
// 每次随机一个 indexes ,然后再从 indexes 中删除
const index = Math.floor(Math.random() * indexes.length);
return arr[indexes.splice(index, 1)];
});
}
第三种,就不新建新的变量了
const shuffle = function (arr) {
let res = arr.slice();
res.forEach((v, i, a, j) => {
j = Math.floor(Math.random() * a.length);
// 从数组中随机获取到一个index,然后交换这两个值
[a[i], a[j]] = [a[j], a[i]];
});
return res;
}