我希望从JS中的同一个数组中获得两个不同的随机项。关于堆栈溢出有一些相关的问题,但我无法理解费舍尔耶茨洗牌是如何工作的。我需要搜索整个数组来检索这些项,但是数组的大小很小。
目前,我有一个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)];
}发布于 2014-02-27 10:41:41
只需对数组进行洗牌,得到前两项:
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];发布于 2014-02-27 10:49:26
你可以这样做,
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);希望能帮上忙。
发布于 2018-04-03 18:56:57
基于@alexey的回答,但使用不同方法对数组进行改组,您可以这样做:
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;
}这样,您就有了一个泛型函数,您只需将数组和想要从数组中返回的随机项(在数组中返回)的数量传递给它。
https://stackoverflow.com/questions/22065563
复制相似问题