📌  相关文章
📜  如何随机排序数组javascript(1)

📅  最后修改于: 2023-12-03 15:24:57.832000             🧑  作者: Mango

如何随机排序数组 JavaScript

在 JavaScript 中,你可以使用几种不同的方法来随机排序一个数组。在本文中,我们将介绍其中三种方法。

Math.random() 方法

使用 Math.random() 方法生成一个介于 0 和 1 之间的随机数。

function shuffle(array) {
  var currentIndex = array.length, temporaryValue, randomIndex;

  while (0 !== currentIndex) {
    randomIndex = Math.floor(Math.random() * currentIndex);
    currentIndex--;

    temporaryValue = array[currentIndex];
    array[currentIndex] = array[randomIndex];
    array[randomIndex] = temporaryValue;
  }

  return array;
}

上面的代码使用了 Fisher-Yates shuffle 算法,你可以在 这里 了解更多相关信息。

lodash.shuffle() 方法

Lodash 是一个流行的 JavaScript 工具库,它为数组提供了一个 shuffle() 方法。

var _ = require('lodash');

var array = [1, 2, 3, 4, 5];

console.log(_.shuffle(array));

上面的代码使用了 lodash.shuffle() 方法来随机排序数组。

Array.sort() 方法

使用 Array.sort() 方法和 Math.random() 函数来随机排序数组。

function compareRandom(a, b) {
  return Math.random() - 0.5;
}

var array = [1, 2, 3, 4, 5];

console.log(array.sort(compareRandom));

上面的代码使用 Array.sort() 方法和 compareRandom() 函数来随机排序数组。compareRandom() 函数返回一个随机值,该值是一个介于 -0.5 和 0.5 之间的数字,因此数组中的元素将被随机排序。

总结

以上是三种 JavaScript 中随机排序数组的方法。其中使用 Math.random() 和 lodash.shuffle() 方法可能是最常见和最简单的。但是,如果你想学习更多有用的算法和技巧,那么使用 Fisher-Yates shuffle 算法和 compareRandom() 函数可能更适合你。