我的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;
它会使用正确的计数随机化它,但它会重复一些。在我随机化之前没有重复过。有人能告诉我他们为什么要重复吗?
感谢。