【问题标题】:Get two different random items from same array in JS从JS中的同一个数组中获取两个不同的随机项
【发布时间】:2014-02-27 10:24:44
【问题描述】:

我希望从 JS 中的同一个数组中获取两个不同的随机项。 Stack Overflow 上有相关的问题,但我不明白Fisher Yates Shuffle 的工作原理。我需要搜索整个数组来检索这些项目,但是数组的大小很小。

目前我有一个 while 循环,但这似乎不是最有效的实现方式:

    var honeyPots = ["Fname", "EmailAddress", "Lname", "Telephone", "Address1", "Address2", "Surname", "Title"]; //Fake field names to dupe the bots!
    var honeyPot = honeyPots[Math.floor(Math.random()*honeyPots.length)]; //Get a random field name from the array
    var honeyPot2 = honeyPots[Math.floor(Math.random()*honeyPots.length)]; //Get a random field name from the array
    while (honeyPot == honeyPot2)
      {
        var honeyPot2 = honeyPots[Math.floor(Math.random()*honeyPots.length)];
      }

【问题讨论】:

    标签: javascript jquery arrays


    【解决方案1】:

    只需打乱数组并获取前两项:

    var honeyPots = ["Fname", "EmailAddress", "Lname", "Telephone", "Address1", "Address2", "Surname", "Title"];
    
    var results = honeyPots
        .sort(function() { return .5 - Math.random() }) // Shuffle array
        .slice(0, 2); // Get first 2 items
    
    var honeyPot = results[0];
    var honeyPot2 = results[1];
    

    【讨论】:

    • 抱歉,有点迂腐,排序功能是否与 Fisher Yates Shuffle 定义的概念相似?
    • 不,这是另一种方法。
    • 这里有一篇关于数组排序方法可视化的优秀文章:bost.ocks.org/mike/shuffle 假设我设置正确,该页面上的最终方法比这个答案中的方法表现更好:@987654322 @。在大多数情况下,可能不需要考虑,而且这里简洁!
    【解决方案2】:

    你可以这样做,

    var arr = [1,2,3,4,4,5,8];
    var randomValue = [];
    for(i=arr.length; i>=0; i--) {
      var randomNum = Math.floor(Math.random() * i);
      randomValue.push(arr[randomNum]);
      if(i==arr.length-1)break;
    }
    console.log(randomValue);
    

    希望对你有帮助。

    【讨论】:

      【解决方案3】:

      基于@alexey-prokhorov 的回答,但使用different method 对数组进行洗牌,您可以执行以下操作:

      var getRandosFromArray = function(array, numRandos){
        var shuffled = shuffle(array)
        var randos = shuffled.slice(0, numRandos)
        return randos
      }
      
      // https://bost.ocks.org/mike/shuffle/
      var shuffle = function(array) {
        var m = array.length, t, i;
      
        // While there remain elements to shuffle…
        while (m) {
      
          // Pick a remaining element…
          i = Math.floor(Math.random() * m--);
      
          // And swap it with the current element.
          t = array[m];
          array[m] = array[i];
          array[i] = t;
        }
      
        return array;
      }
      

      这样你就有了一个通用函数,你可以向它传递一个数组和你想要从它返回的随机项的数量(在数组中返回)。

      【讨论】:

        猜你喜欢
        • 2014-02-18
        • 2011-01-20
        • 1970-01-01
        • 1970-01-01
        • 2021-07-08
        • 1970-01-01
        • 1970-01-01
        • 2019-05-17
        • 1970-01-01
        相关资源
        最近更新 更多