mardi 15 septembre 2015

Javascript Generate Random Number without Repeating

Little bit new to Javascript so I'm playing around with it but I've come across a problem, I have some code where I have an array of x amount of items. In this case, videos, and I want to randomly call a video, however If the current video already called is the same as the random number I want it to generate another random number until it's unique.

Here's my code -

var videoLinks = [
    ['<iframe id="vid" src="https://www.youtube.com/embed/nYm2G4MnSkY?autoplay=1" frameborder="0" allowfullscreen></iframe>'],
    ['<iframe id="vid" src="https://www.youtube.com/embed/wAgZVLk6J4M?autoplay=1&start=5&end=45" frameborder="0" allowfullscreen></iframe>'],
    ['<iframe id="vid" src="https://www.youtube.com/embed/ix9wpslKwBE?autoplay=1" frameborder="0" allowfullscreen></iframe>'],
    ['<iframe id="vid" src="https://www.youtube.com/embed/OJJ-iLsQOPc?autoplay=1&iv_load_policy=3" frameborder="0" allowfullscreen></iframe>'],
    ['<iframe id="vid" src="https://www.youtube.com/embed/rore790l_sk?autoplay=1&start=12&end=94" frameborder="0" allowfullscreen></iframe>'],
];

var randomNumber = function () {
    var getRandomNumber = Math.floor(Math.random() * 5);
    var random = videoLinks[getRandomNumber]
    document.getElementById("videoWrapper").innerHTML = random[0];
};

randomNumber(); // To call the function on load




Aucun commentaire:

Enregistrer un commentaire