如何将数组随机打乱顺序?
时间: 2024-02-11 14:06:49 浏览: 25
在 JavaScript 中,可以使用 Fisher-Yates 洗牌算法(也称为 Knuth 洗牌算法)将一个数组随机打乱顺序。该算法的基本思路是从数组末尾开始,依次将当前位置的元素与前面随机位置的元素互换,直到整个数组都被遍历一遍。这样可以保证每个元素都有相同的概率出现在每个位置上。以下是一个示例实现:
```javascript
function shuffle(array) {
var currentIndex = array.length;
var temporaryValue, randomIndex;
// While there remain elements to shuffle...
while (0 !== currentIndex) {
// Pick a remaining element...
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex -= 1;
// And swap it with the current element.
temporaryValue = array[currentIndex];
array[currentIndex] = array[randomIndex];
array[randomIndex] = temporaryValue;
}
return array;
}
```
这个函数会接收一个数组作为参数,然后返回一个随机打乱顺序后的新数组。该函数使用了 while 循环和 Math.random() 函数,每次循环都会将当前位置的元素与前面随机位置的元素互换,直到整个数组都被遍历一遍。最后返回打乱顺序后的新数组。
示例用法:
```javascript
var arr = [1, 2, 3, 4, 5];
var shuffledArr = shuffle(arr);
console.log(shuffledArr); // [3, 5, 4, 1, 2] 或者其他任意顺序的数组
```