1
我试图随机加载一些图像到页面的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
我严重怀疑那个代码会导致堆栈溢出错误。 – Pointy
在你的while循环中,如果if条件为false,toponum永远不会被减少。 –
@GerardoFurtado,你的建议可能是唯一的溢出原因。如果我是你,我会将这个评论推广到一个答案。 – tafa