在JS中从同一个数组中获取两个不同的随机项

Bar*_*ney 2 javascript arrays jquery

我想从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)];
      }
Run Code Online (Sandbox Code Playgroud)

Ale*_*rov 7

只需将数组洗牌并获得前两项:

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];
Run Code Online (Sandbox Code Playgroud)