window.onload = start;
function start () {
var name = ["Hans","Ole","Nils","Olav","Per","Knut","Kari","Line","Pia"]
var random = Math.floor(Math.random()*8)
var random2 = Math.floor(Math.random()*8)
var random3 = Math.floor(Math.random()*8)
var name2 = []
name2.push(name[random])
name2.push(name[random2])
name2.push(name[random3])
for(i=0; i<3; i++) {
document.getElementById("par").innerHTML += name2[i] + "<br/>" ;
}
}
到目前为止,使用此代码,我可以从名称数组中生成3个随机名称。但我希望这三个名字不要重复,我不知道如何实现这一点。
答案 0 :(得分:0)
我创建了一个使用递归的解决方案。
函数 randomNames 重复三次。每次调用count都会增加,而名称是一个没有已经采用的名称的数组。它返回一个包含三个随机名称的数组。
function start () {
var name = ["Hans","Ole","Nils","Olav","Per","Knut","Kari","Line","Pia"]
function randomNames(count, names) {
if(count >= 3) return [];
var random = Math.floor(Math.random()*(names.length-1));
// remove current name
var name = names.splice(random, 1);
return randomNames(++count, names).concat(name);
}
var random = randomNames(0, name);
}
答案 1 :(得分:0)
您可以对所选项目使用哈希表,并进行检查,直到找到所有需要的项目。
window.onload = start;
function start() {
var name = ["Hans", "Ole", "Nils", "Olav", "Per", "Knut", "Kari", "Line", "Pia"],
hash = {},
random;
while (Object.keys(hash).length < 3) {
do {
random = Math.floor(Math.random() * name.length);
} while (hash[random])
hash[random] = true;
document.getElementById("par").innerHTML += name[random] + "<br/>";
}
}
<div id="par"></div>
ES6与Set
window.onload = start;
function start() {
var name = ["Hans", "Ole", "Nils", "Olav", "Per", "Knut", "Kari", "Line", "Pia"],
hash = new Set,
random;
while (hash.size < 3) {
do {
random = Math.floor(Math.random() * name.length);
} while (hash.has(random))
hash.add(random);
document.getElementById("par").innerHTML += name[random] + "<br/>";
}
}
<div id="par"></div>
答案 2 :(得分:-1)
将random2和random 3的赋值替换为:
var random = Math.floor(Math.random()*8);
var random2, random3;
do {
random2 = Math.floor(Math.random()*8);
} while (random2==random);
do {
random3 = Math.floor(Math.random()*8);
} while (random3==random || random3==random2);
答案 3 :(得分:-1)
也许这可能会有所帮助。我随机化了数组的顺序,然后选择前三个元素。这允许零重复名称并在每次运行函数时生成新的答案。不确定你的HTML是什么样的,所以我只是添加了id&#34; demo&#34;。
var players = ["Hans","Ole","Nils","Olav","Per","Knut","Kari","Line","Pia"];
function tournament() {
var names = [];
players.sort(function(a,b){return 0.5 - Math.random()});
for (i=0; i<3; i++){
names.push(players[i]);
}
document.getElementById("demo").innerHTML = names;
}
function tournament() {
var names = [];
players.sort(function(a,b){return 0.5 - Math.random()});
for (i=0; i<3; i++){
names.push(players[i]);
}
document.getElementById("demo").innerHTML = names;
}