js实现乱序
使用 sort 和 Math.random 实现乱序
通过 Array.prototype.sort 结合 Math.random 实现简单乱序。Math.random() 生成 0 到 1 的随机数,sort 方法根据返回值决定排序顺序。
const array = [1, 2, 3, 4, 5];
const shuffled = array.sort(() => Math.random() - 0.5);
console.log(shuffled); // 输出乱序后的数组
注意:此方法在部分情况下可能无法保证完全均匀的随机性,适用于简单场景。

Fisher-Yates 洗牌算法
Fisher-Yates 算法是一种高效且均匀的乱序方法,通过遍历数组并随机交换元素实现。
function shuffle(array) {
for (let i = array.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[array[i], array[j]] = [array[j], array[i]];
}
return array;
}
const array = [1, 2, 3, 4, 5];
console.log(shuffle(array)); // 输出乱序后的数组
该方法的时间复杂度为 O(n),且能保证每个元素出现在每个位置的概率均等。

使用 lodash 库的 _.shuffle
如果需要快速实现且不关注底层细节,可以使用 lodash 提供的 _.shuffle 方法。
const _ = require('lodash');
const array = [1, 2, 3, 4, 5];
console.log(_.shuffle(array)); // 输出乱序后的数组
lodash 的实现基于 Fisher-Yates 算法,适合在项目中直接调用。
注意事项
- 均匀随机性:
sort结合Math.random的方式可能在某些 JavaScript 引擎中分布不均匀,Fisher-Yates 是更可靠的选择。 - 性能:对于大型数组,Fisher-Yates 算法性能优于
sort。 - 不可变操作:上述方法会修改原数组,如需保留原数组,可先创建副本:
const shuffled = [...array].sort(() => Math.random() - 0.5);






