所以我想从一个名称数组中找到三个名称,然后我想将其写入一个新数组(虽然还没有做到这一点),但我遇到的问题是它不断随机化我已经存在的相同名称找到了。
查看 jsfiddle script .
代码:
findStudentBtn.onclick = findStudent;
function findStudent() {
var studArray = ["John","Daniel","Hans","Lars","Tom","Amanda","Jane","Sarah"] //1-8
for (i=0; i<3; i++) {
if (i=1) {
var randomStud1 = studArray[Math.floor(studArray.length * Math.random())];
msg8.innerHTML += randomStud1 + ", ";
}
if (i=2) {
var randomStud2 = studArray[Math.floor(studArray.length * Math.random())];
msg8.innerHTML += randomStud2 + ", ";
}
if (i=3) {
var randomStud3 = studArray[Math.floor(studArray.length * Math.random())];
msg8.innerHTML += randomStud3 + ", ";
}
if (randomStud1 == randomStud2 || randomStud2 == randomStud3 || randomStud1 == randomStud3){
ms8.innerHTML = "";
findStudent();
}
}
}
最佳答案
对于任何对解决方案感兴趣但又不愿意使用 jsfiddle 的人来说,这是我使用的脚本。
findStudentBtn.onclick = function(){
findStudent();
};
var r_stud = ["John","Daniel","Hans","Lars","Tom","Amanda","Jane","Sarah"];
var r_rndm = [];
var r_newr = [];
function getStudent(){
//if the amount of available people, is to small to reach 3.
if(r_rndm.length == r_stud.length){
//reset the random selected array
r_rndm = [];
return r_newr;
}
//select a student
var i_randomStudent = Math.floor(r_stud.length * Math.random());
var s_randomStudent = r_stud[i_randomStudent];
if(r_rndm.indexOf(s_randomStudent) >= 0){
//if it's allready been selected, try again.
getStudent();
}else{
//add students to new selection and to alltime selection
r_rndm.push(s_randomStudent);
r_newr.push(s_randomStudent);
//return the new array
return r_newr;
}
};
function findStudent(){
//reset new array.
r_newr = [];
for(i = 0; i < 3; i++){
getStudent();
};
//print contents of new array to console.
console.log(r_newr);
for(i = 0; i < r_newr.length; i++){
separator = (i == r_newr.length - 1 && r_rndm.length == 0 ) ? '' : ', ';
msg8.innerHTML += r_newr[i] + separator;
}
};
关于javascript - 数学随机在数组中查找名称而不重复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32822252/