我正在寻找从JS中的同一数组中获得两个不同的随机项。关于堆栈溢出有一些相关的问题,但是我无法理解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)];
}
最佳答案
只需将数组改组并获得前两个项目:
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];