0

我的 Javascript 数组在我想要的位置正确显示,但现在我试图在迭代之前随机化数组。数组内容将始终相同,但我希望用户每次都能看到它们以不同的顺序显示。我在下面尝试了一些代码:

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;

我对这一切都很陌生,任何帮助都将不胜感激。

我在下面更新了我的代码。

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;

它确实以正确的计数随机化它,但它会重复一些。在我随机化之前它没有重复。有人能告诉我他们为什么重复吗?

谢谢。

4

0 回答 0