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个随机名称。但是我不希望重复这3个名字,而且我不知道该怎么做。
最佳答案
将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);
在这里尝试:https://jsfiddle.net/o04tf9ct/