js 实现数组乱序
方法一:使用 sort 结合随机数
通过 Math.random() 生成随机数,利用 sort 方法随机排序数组元素。这种方式简单但存在一定的偏差,因为 sort 的排序算法可能不完全随机。
const shuffleArray = (arr) => {
return arr.sort(() => Math.random() - 0.5);
};
const array = [1, 2, 3, 4, 5];
console.log(shuffleArray(array));
方法二:Fisher-Yates 洗牌算法
Fisher-Yates 算法是一种高效且完全随机的乱序方法。从数组末尾开始,依次与随机位置的元素交换。
const shuffleArray = (arr) => {
for (let i = arr.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[arr[i], arr[j]] = [arr[j], arr[i]];
}
return arr;
};
const array = [1, 2, 3, 4, 5];
console.log(shuffleArray(array));
方法三:使用 Array.map 结合随机值
通过为每个元素分配随机值,然后根据随机值排序。这种方式类似于方法一,但更直观。
const shuffleArray = (arr) => {
return arr
.map((value) => ({ value, sort: Math.random() }))
.sort((a, b) => a.sort - b.sort)
.map(({ value }) => value);
};
const array = [1, 2, 3, 4, 5];
console.log(shuffleArray(array));
方法四:使用 Lodash 库的 _.shuffle
如果项目中已引入 Lodash,可以直接使用其 _.shuffle 方法实现乱序。
const _ = require('lodash');
const array = [1, 2, 3, 4, 5];
console.log(_.shuffle(array));
注意事项
- Fisher-Yates 算法是推荐的标准实现,因为它的随机性更均匀。
- 方法一和方法三的随机性可能不够完美,适合对随机性要求不高的场景。
- Lodash 的
_.shuffle内部也采用 Fisher-Yates 算法,适合直接调用。






