【发布时间】: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