【问题标题】:randomize objects in array [duplicate]随机化数组中的对象[重复]
【发布时间】:2025-11-21 23:10:01
【问题描述】:

我有一个array,每当buttonclicked 时,它会渲染 25 个图像/引脚,并且它只渲染array 中的前 25 个图像/引脚。我希望它一次渲染 25 个引脚,但希望每次单击 button 时它们都是 random

有人建议我使用之前在此处设置的答案的一部分,但我无法弄清楚如何应用它或理解我所拥有的。

这是我被告知要使用的:

randomIndex = Math.floor(Math.random() * currentIndex);

用我想要的array加上.length替换当前索引。

var pinIdArray = ["448460075380400214", "554857616577037440", "129619295506364205"];					
var boardIdArray = [];
var showPins = [];
      
function(){
  res.render("suggested", {pins: showPins});

【问题讨论】:

    标签: javascript arrays random shuffle


    【解决方案1】:

    您可以使用Durstenfeld shuffle 对数组进行洗牌,然后取出数组中的前 25 个元素。

    function shuffleArray(array) {
      for (var i = array.length - 1; i > 0; i--) {
        var j = Math.floor(Math.random() * (i + 1));
        var temp = array[i];
        array[i] = array[j];
        array[j] = temp;
      }
      return array;
    }
    
    var array = [];
    for(var i = 0; i < 500; i ++) {
        array[i] = i;
    }
    console.log(shuffleArray(array).slice(0, 25));

    【讨论】:

      【解决方案2】:

      您可以使用Lodash's _.shuffle 函数对数组中的值进行随机化/随机化。 Lodash _.shuffle 函数使用 Fisher-Yates shuffle 的一个版本。

      var array = [1, 2, 3, 4];
      var result = _.shuffle(array)
      console.log(result);
      &lt;script src="https://cdn.jsdelivr.net/lodash/4.17.4/lodash.min.js"&gt;&lt;/script&gt;

      【讨论】:

        【解决方案3】:

        这是一个用 Javascript 实现的函数,没有任何库。这也避免了对数组进行洗牌,因此应该更快。

        let pinIdArray = ["448460075380400214", "554857616577037440", "129619295506364205", "3403722138", "8005795986", "7717201977", "6689430878", "7705363504", "3827905985", "9133621064", "9162201846", "2655432017", "0197893312", "7220269979", "3218703261", "3478813716", "7445481990", "9806757977", "9357022147", "3492330721", "3504169963", "9259212333", "6574699545", "9727263383", "0016479256", "1624997250", "2083975447", "5683391989", "3466001901", "4660933902", "5216511997", "8820216343", "8583764035", "4563326839", "5201961267", "3429608185", "5007846054", "7437408815", "3472117054", "1545827364", "3152159572", "7913372317", "2550237417"];
        
        function getRandomSubset(array, setSize) {
          let maxValue = array.length, tmpSet = new Set(), randomIndices;
          if (maxValue <= setSize) {
            randomIndices = [...Array(setSize).keys()];
          } else {
            while (tmpSet.size < setSize) {
              tmpSet.add(Math.floor(Math.random() * maxValue));
            }
            randomIndices = Array.from(tmpSet)
          }
          return randomIndices.map(index => array[index]);
        }
        
        //function(){
        //  res.render("suggested", {pins: getRandomSubset(pinIdArray, 25)});
        
        // Test
        console.log("25 Random Elements:", getRandomSubset(pinIdArray, 25));

        【讨论】: