我正在尝试将一些图像随机加载到页面的html div中,我的代码有时会工作,就像在第一页加载时一样,但是在第二页或第三页上它可能导致页面空白并缓冲并崩溃标签。 这是一个指向完整文件的链接(不包括图像srcs):
这是完整的js文件:(小心,因为如果重新加载几次会导致选项卡崩溃) https://repl.it/GBvG/2
var topnum = 7; //will later be used to represent current index
var rando; //will later be used as a swap index
var temporary; //will later be used as a temporary holder so we can swap rando and topnum
var myCard = document.getElementsByClassName('card');
var myArray = [
'Images/aceheart.png',
'Images/aceheart.png',
'Images/kingheart.png',
'Images/kingheart.png',
'Images/queenheart.png',
'Images/queenheart.png',
'Images/tenheart.png',
'Images/tenheart.png'
];
function create(){
while(topnum > 0){ //loops over all 8 elements
rando = Math.floor((Math.random() * topnum) + 0);
//will swap elements as long as the random index we got is not the same as the current index
if(myArray[rando] !== myArray[topnum]){
temporary = myArray[topnum];
myArray[topnum] = myArray[rando]; //randomizes topindex value
myArray[rando] = temporary;
topnum--;
}; // end of if
}; //end of while
for(var i = 0; i <= 8;i++){
var imgElement = "<img src='" + myArray[i] + "' alt='test' width='200px' height='275px'/>";
myCard[i].innerHTML = imgElement;
}; //end of for loop
}; // end of create
我几乎肯定问题在于这个片段,虽然我不知道为什么:
for(var i = 0; i <= 8;i++){
var imgElement = "<img src='" + myArray[i] + "' alt='test' width='200px' height='275px'/>";
myCard[i].innerHTML = imgElement;
}; //end of for loop
答案 0 :(得分:4)
你有8张卡,但你的循环运行了9次。
更改
for(var i = 0; i <= 8;i++)
要
for(var i = 0; i < 8;i++) // use `<` instead of `<=`
此外,正如Gerardo Furtado在评论中提到的那样,您应该将topnum--
放在if
循环中while
之外。否则你将有一个无限循环。
while(topnum > 0) {
rando = Math.floor((Math.random() * topnum) + 0);
if(myArray[rando] !== myArray[topnum]){
// ...
}
topnum--; // <-- move the decrement here
}