这是最近面试遇到的,不过忘记了,之前也有印象刷到过这道题,就再次记录一下加深印象吧,听到最多的答案是利用sort方法,不过也有说这种方法不好,利用了快排和插入排序,那就整理下吧
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<meta name="author" content="杨欣">
<title>js之数组乱序</title>
</head>
<body>
<script>
// 1.使用sort方法
let arr1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
let arr2 = arr1.sort(() => Math.random() - 0.5)
console.log('1111111', arr2);
// 2.把随机的放入新数组,最后合并在一起
let arr3 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
const shuffle1 = (arr) => {
let len = arr.length;
let newArr = [];
for (let i = 0; i < len; i++) {
let index = Math.floor(Math.random() * arr.length);
newArr.push(arr[index])
arr.splice(index, 1)
}
return [...newArr, ...arr]
}
console.log('2222222', shuffle1(arr3));
// 3.洗牌算法,取出最后一个和得到的随机交换位置
let arr4 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
const shuffle2 = (arr) => {
for (let i = arr.length; i; i--) {
let j = Math.floor(Math.random() * i)
[arr[i - 1], arr[j]] = [arr[j], arr[i - 1]]
}
return arr
}
console.log('3333333', shuffle1(arr4));
</script>
</body>
</html>