我希望在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)];
}
答案 0 :(得分: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];
答案 1 :(得分:0)
你可以这样做,
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);
希望它有所帮助。
答案 2 :(得分:0)
根据@ 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;
}
这样你就有了一个泛型函数,你只需要传递一个数组,以及你想要从中返回的随机项(在数组中返回)。