0

I have my Javascript Array displaying properly where I want it to but now I am trying to randomize the array before I iterate through it. The array contents will always be the same but I want the user to see them displayed in a different order each time. I tried some code below:

var lastloaded = 0;
window.onload = loadPages;

function loadPages() {
    var arr = ["aCard.html", "bCard.html", "cCard.html", "dCard.html"];

    function shuffle() {
        var m = arr.length,
            t, i;

        // While there remain elements to shuffle…
        while (m) {

            // Pick a remaining element…
            i = Math.floor(Math.random() * m--);

            // And swap it with the current element.
            t = arr[m];
            arr[m] = arr[i];
            arr[i] = t;
        }

        return array;
    }
    var frame = document.getElementById("frameWrap");
    if (lastloaded + 1 > array.length) {
        lastloaded = window.location = "greatJob.html";
    }
    frame.src = array[lastloaded];
    lastloaded++;
}

document.getElementById('tom').onclick = loadPages;

I am new to all this and any help will be greatly appreciated.

I updated my code to this below.

var lastloaded = 0;
window.onload = loadPages;

function shuffle(array) {
    var m = array.length, t, i;

// While there remain elements to shuffle…
while (m) {

// Pick a remaining element…
i = Math.floor(Math.random() * m--);

// And swap it with the current element.
t = array[m];
array[m] = array[i];
array[i] = t;
}

return array;
}

function loadPages () {
     var arr = ["aCard.html", "bCard.html", "cCard.html", "dCard.html"];
    var frame = document.getElementById("frameWrap");
        shuffle(arr);
    if (lastloaded+1>arr.length){
        lastloaded = window.location = "greatJob.html";
    }
    frame.src = arr[lastloaded];
    lastloaded++;
    }
    document.getElementById('tom').onclick = loadPages;

It does randomize it with the right count but it repeats some. It didn't repeat before I randomized it. Can someone tell me why they are repeating?

Thanks.

eckes
  • 64,417
  • 29
  • 168
  • 201

0 Answers0