Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using an array element only once

I am new to JavaScript and I would like to get three random elements out of my array, which need to be different. I already managed to get three different elements, then I tried to take one element only once via the split method. But apparently this doesn't really work, there are probably a lot of mistakes since this is one of my first scripts. Also it sometimes says "undefined".

http://jsfiddle.net/t4mtpm50/

HTML:

<span id="tot1"></span>, <span id="tot2"> und </span> und <span id="tot3"></span>

Javascript:

function getNumber() {
    random = Math.floor(Math.random() * students.length);
    students.splice(random,1);
    return random;
}

students = new Array("Paul", "Jan", "Fabian D.", "Fabian K.", "Lennard", 
                            "Robin", "Angelique", "Joyce", "Sarah", "Ajlin",
                            "Enes", "Leon", "Boran", "Joshua")    

getNumber();
tot1 = students[random];
getNumber();
tot2 = students[random];
getNumber();
tot3 = students[random];

document.getElementById('tot1').innerHTML = tot1;
document.getElementById('tot2').innerHTML = tot2;
document.getElementById('tot3').innerHTML = tot3;
like image 906
Simon Mathewson Avatar asked Dec 05 '22 05:12

Simon Mathewson


1 Answers

By using .splice(), the randomly selected name is actually being removed before it's retrieved, making random instead refer to the next name in the collection:

var students = [ "Paul", "Jan", "Fabian D." ];
var random = 1;

console.log(students[random]); // "Jan"

students.splice(random, 1);

console.log(students);         // [ "Paul", "Fabian D." ]
console.log(students[random]); // "Fabian D."

The "it sometimes says 'undefined'" happens when random tries to refer to the last element:

var students = [ "Paul", "Jan", "Fabian D." ];
var random = 2;

console.log(students[random]); // "Fabian D."

students.splice(random, 1);

console.log(students);         // [ "Paul", "Jan" ]
console.log(students[random]); // undefined, random is now out-of-bounds at 2

You could put to use the return value of .splice(), which is a collection of the removed elements, redefining getNumber() to instead return an element rather than an index:

function getStudent() {
    var random = Math.floor(Math.random() * students.length);
    return students.splice(random, 1)[0]; // return the 1st and only removed element
}

var tot1 = getStudent(); // "Fabian D."
var tot2 = getStudent(); // "Enes"
var tot3 = getStudent(); // "Joyce"

http://jsfiddle.net/6gox6L1t/

like image 67
Jonathan Lonowski Avatar answered Dec 09 '22 14:12

Jonathan Lonowski