我创建了一个连接到图像数组的随机数生成器,其中一个图像在加载页面时随机显示给用户。
我正在努力弄清楚如何将这些图像中的一个放在本地存储器中,以便在重新加载页面时不会出现相同的图像,我只是不知道该怎么做。
这是我的JSFiddle,如果你需要它,我不知道如何在这些上显示图像虽然我希望这不会导致问题:https://jsfiddle.net/Syystole/10mxjs9v/4/
HTML
<img src="" width="305" height="312" id="myPicture" alt="some image">
JS
window.onload = choosePic; // Run Function When Website Runs
var myPix = new Array("./images/service2.png","./images/service3.png","./images/service4.png"); //Array of 3
function choosePic() {
randomNum = Math.floor((Math.random() * myPix.length)); //Random Number Generator based on the number of pictures in array
document.getElementById("myPicture").src = myPix[randomNum]; //Random Number with image is set in HTML
}
答案 0 :(得分:0)
选择时,您可以将最后一张图像的索引存储在本地存储中:
localStorage.setItem('lastViewedImage', randomNum);
然后在运行您的choosePic时检查最后查看的图像索引,并处理不选择同一图像,但您认为合适:
var lastViewedImage = localStorage.getItem('lastViewedImage');
if (lastViewedImage == randomNum) {
// Handle collision
}
编辑:
function choosePic {
// Get the index of the last viewed image
var lastViewedImage = localStorage.getItem('lastViewedImage');
// Use a temp array as not to modify the array storing the images
var tempArr = myPix;
if (lastViewedImage != null) {
// Remove the used image from the temp copy of the picture array
tempArr.splice(lastViewedImage, 1);
}
//Random Number Generator based on the number of pictures in temp array
var randomNum = Math.floor(Math.random() * tempArr.length);
// Update the stored index with the new used images index
localStorage.setItem('lastViewedImage', randomNum);
//Random Number with image is set in HTML
document.getElementById("myPicture").src = myPix[randomNum];
}
编辑2:
这实际上是一个糟糕的解决方案。由于使用的索引是临时数组中项的索引,因此索引不会应用于在后续执行函数时生成的临时数组。希望这会给你一些关于如何解决问题的想法。
答案 1 :(得分:0)
您可以循环使用随机数字选择,直到它与上一个选择的数字不同为止 注意 - 由于随机性的性质,你可以一遍又一遍地使用相同的数字,并最终循环数十亿次,这会杀死你的页面,但由于概率的性质,这种情况发生的可能性是可忽略的。
// somewhere
var myPix = new Array("./images/service2.png","./images/service3.png","./images/service4.png");
function choosePic() {
// Get the last number stored.
var lastViewedImage = localStorage.getItem('lastViewedImage');
// Set a very high number if none was stored before.
if (lastViewedImage === null) lastViewedImage = 65535;
// Keep looping as long as we come up with the same number.
var random = 0;
do {
random = Math.floor((Math.random() * myPix.length));
} while (random === lastViewedImage);
// Got a different number, save it and return the image
localStorage.setItem('lastViewedImage', random);
return myPix[random];
}
// Use as:
document.getElementById("myPicture").src = choosePic();
这会对choosePic
函数中的图像数组的名称进行硬编码,这通常被认为是不好的做法;你可以将数组传递给choosePic,但是如果你传递不同的数组,那么应该考虑如何处理随机数(左边作为读者的练习)。