写个方法随机打乱一个数组
在前端开发中,你可以使用JavaScript的Array.prototype.sort()方法和Math.random()函数来随机打乱一个数组。下面是一个示例方法:
function shuffleArray(array) {
let currentIndex = array.length, temporaryValue, randomIndex;
// 当仍剩余元素需要混洗时
while (0 !== currentIndex) {
// 选取一个剩余元素...
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex -= 1;
// 并与当前元素交换。
temporaryValue = array[currentIndex];
array[currentIndex] = array[randomIndex];
array[randomIndex] = temporaryValue;
}
return array;
}
// 使用示例
const originalArray = [1, 2, 3, 4, 5, 6, 7, 8, 9];
const shuffledArray = shuffleArray(originalArray);
console.log(shuffledArray); // 输出打乱后的数组
这个方法使用了Fisher-Yates(也称为Knuth)洗牌算法,它是一种高效的、能生成无偏置的随机排列的算法。在这个算法中,我们遍历数组,并在每次迭代中随机选择一个元素与当前元素交换。这样,每个元素都有机会被移动到新的位置,从而实现数组的随机打乱。
浙公网安备 33010602011771号