JavaScript实现将一组字符串乱序输出
js代码可以通过两种方法来实现乱序输出。
**方法1:使用 sort() + Math.random()**
实现原理:使用数组的 sort() 方法和 Math.random() 函数。在 sort() 方法中传入一个比较函数,该函数返回一个随机数,表示每个元素应该放在哪个位置。
代码如下:
```
function shuffle(array) {
array.sort(() => Math.random() - 0.5);
}
const myArray = [1, 2, 3, 4, 5];
shuffle(myArray);
console.log(myArray);
```
**方法2:使用 Fisher–Yates 算法**
实现原理:Fisher–Yates 算法(也称为 Knuth shuffle)是一种用于打乱数组顺序的常见算法。该算法的基本思想是从数组的末尾开始,随机选取一个元素并交换位置,然后再从数组的前面选取一个元素并交换位置,以此类推。
代码如下:
```
function shuffle(array) {
let currentIndex = array.length;
let randomIndex;
// 从数组末尾开始,逐个交换元素位置
while (currentIndex !== 0) {
// 随机选取一个元素
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex--;
// 交换元素位置
[array[currentIndex], array[randomIndex]] = [array[randomIndex], array[currentIndex]];
}
return array;
}
const myArray = [1, 2, 3, 4, 5];
shuffle(myArray);
console.log(myArray);
```
我的笔记