js实现重排
实现数组重排
使用Array.prototype.sort()方法结合随机数生成器实现数组元素的随机重排。这种方法通过比较函数返回随机正负值打乱原有顺序。
function shuffleArray(array) {
return array.sort(() => Math.random() - 0.5);
}
Fisher-Yates洗牌算法
经典的Fisher-Yates算法通过逆向遍历数组并随机交换元素实现高效重排,时间复杂度为O(n)。这是目前最推荐的标准实现方式。
function fisherYatesShuffle(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;
}
使用ES6特性简化
利用扩展运算符和箭头函数可以写出更简洁的现代JavaScript实现:
const modernShuffle = arr =>
[...arr].reduceRight((res, _, i, a) =>
(res.push(a.splice(Math.floor(Math.random() * (i + 1)), 1)[0]), res), []);
性能优化版本
对于大型数组,使用位运算和类型化数组可以提升性能:
function optimizedShuffle(array) {
const typedArray = new Uint32Array(array.length);
crypto.getRandomValues(typedArray);
return array.reduce((shuffled, _, i) => {
const j = typedArray[i] % (i + 1);
if (j !== i) [shuffled[i], shuffled[j]] = [shuffled[j], shuffled[i]];
return shuffled;
}, [...array]);
}
不可变重排实现
保持原数组不变的情况下返回新数组:

const immutableShuffle = arr => {
const copy = [...arr];
for (let i = copy.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[copy[i], copy[j]] = [copy[j], copy[i]];
}
return copy;
};






