以前项目中常用的打乱数组的方法
[1,2,3,4,5,6].sort(function(){
return Math.random() - 0.5
})
或者使用更简洁的ES6代码
[(1, 2, 3, 4, 5, 6)].sort(() => Math.random() - 0.5)
但是,实际上这种方法并不能真正的随机打乱数组,每个元素有很大几率还在它原来的位置附近出现。
具体原因,这里不做详细介绍,想要了解的可以自行搜索
目前最佳解决方法: Fisher–Yates shuffle 洗牌算法
function shuffle(arr) {
let i = arr.length;
while (i) {
let j = Math.floor(Math.random() * i--);
[arr[j], arr[i]] = [arr[i], arr[j]];
}
}
let arr = [1,2,3,4,5,6,7]
shuffle(arr)
console.log(arr)