lundi 28 septembre 2015

Math random to find Names in an Array while not duplicating

So I want to find three names out of an array of names which I then want to write to a new array (not gotten this far yet though), but the problem I have is that it keeps randomizing the same names I already found.

Check out the jsfiddle script.

Code:

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();
        } 
    }
}  




Aucun commentaire:

Enregistrer un commentaire