如何在JavaScript中正确实现循环数组
我目前正在开发一小段JavaScript,通过按下按钮,使页面背景图像在一系列图片中循环 但是,一旦用户到达最后一张图片,阵列就不会循环回到开始 我不完全确定发生了什么,但当我实现会话存储以使背景图像在页面重新加载和加载期间保持不变时,问题就出现了 我使用的代码如下所示:如何在JavaScript中正确实现循环数组,javascript,arrays,Javascript,Arrays,我目前正在开发一小段JavaScript,通过按下按钮,使页面背景图像在一系列图片中循环 但是,一旦用户到达最后一张图片,阵列就不会循环回到开始 我不完全确定发生了什么,但当我实现会话存储以使背景图像在页面重新加载和加载期间保持不变时,问题就出现了 我使用的代码如下所示: var bodyObj, imgSrc, index; bodyObj = document.getElementById('bgChange'); // For the button used to trigger the
var bodyObj, imgSrc, index;
bodyObj = document.getElementById('bgChange'); // For the button used to trigger the image change)
index = 0;
imgSrc = ['', 'jill.gif', 'shimmer.gif', 'lightpollution.gif', 'crystal.gif', 'rain.gif', 'puke.gif', 'town.gif']; // The array of pictures
maxIndex = Object.keys(imgSrc).length;
function updateIndex() { // The cyclic array
index += 1;
if (index > maxIndex) {
index = 0;
}
sessionStorage.clear(); // Session storage
sessionStorage.setItem('img', JSON.stringify(imgSrc[index]))
}
window.onload = function() { // Session storage
main.style.backgroundImage = 'url("' + JSON.parse(sessionStorage.getItem('img')) + '")';
main.style.backgroundSize = "cover";
};
bodyObj.onclick = function() { // Trigger background image change on button press
main.style.backgroundImage = 'url("' + JSON.parse(sessionStorage.getItem('img')) + '")';
main.style.backgroundSize = "cover";
updateIndex();
}
在updateIndex函数中,使用
if(index>maxIndex-1)
因为数组索引从0开始。如果长度为5,则索引以4结尾(代表问题作者发布解决方案)
该死,现在我觉得自己更笨了。我记得在我试图找出会话存储的时候,多次按Ctrl+Zing组合键浏览代码,所以这可能就是我成功完成这一愚蠢任务的原因。谢谢,pointy和doc。你可能想要
index>=maxIndex
,因为JavaScript数组从0开始。或者@pointy在问题的评论中写道index>=maxIndex
。是的,没有看到你的评论