js实现乱序
使用 Fisher-Yates 洗牌算法
Fisher-Yates 算法是一种高效且均匀的乱序方法。其核心思想是从数组末尾开始,随机选择一个元素与当前元素交换。
function shuffleArray(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;
}
使用 sort() 结合随机数
这种方法利用比较函数的随机返回值实现乱序,但需要注意其随机性可能不够均匀。

function randomSort(array) {
return array.sort(() => Math.random() - 0.5);
}
使用 lodash 库的 shuffle 方法
如果项目中已使用 lodash 库,可以直接调用其 shuffle 方法。

const _ = require('lodash');
const shuffled = _.shuffle([1, 2, 3, 4]);
创建新数组的乱序方法
该方法通过从原数组随机抽取元素构建新数组实现乱序。
function randomizeArray(array) {
const newArray = [];
while (array.length > 0) {
const randomIndex = Math.floor(Math.random() * array.length);
newArray.push(array.splice(randomIndex, 1)[0]);
}
return newArray;
}
性能考虑
对于大型数组,Fisher-Yates 算法是最优选择,时间复杂度为 O(n)。sort() 方法的时间复杂度为 O(n log n),而创建新数组的方法由于频繁使用 splice(),性能会受到影响。
注意事项
Math.random() 生成的伪随机数不适合加密场景。在需要加密级随机性的情况下,应使用 crypto.getRandomValues()。






