为什么我要逐步遍历数组,而不能向后遍历? [英] Why can I step through through my array going forward, but not backwards?
本文介绍了为什么我要逐步遍历数组,而不能向后遍历?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个数组,我每次用户单击按钮时都试图在两个方向上逐步完成.每次单击下一步"时,它都会正确执行,但是,如果单击上一步",则不会以相反的方向执行.为什么?
I have an array I'm trying to step through through in both directions each time a user clicks a button. Each time I click next, it steps through correctly, however, if I click previous, it doesn't step through on the opposite direction. Why?
JS
var i = 0;
var images = ["Hello", "Goodbye", "Hola", "Adios"];
$("#next").on("click", function(){
if(i <= images.length - 1){
$("#result").children("p").remove();
$("#result").append("<p>" +images[i++] +"</p>");
}
})
$("#prev").on("click", function(){
if(i > 0){
$("#result").children("p").remove();
$("#result").append("<p>" +images[i--] +"</p>");
}
})
HTML
<button id="prev">Previous</button>
<div id="result"></div>
<button id="next">Next</button>
编辑:如果我将前一个按钮的条件更改为if(i > 0)
,这也是不期望的,那么会发生什么.
Here's what happens if I change the conditional for the previous button to be if(i > 0)
which is also not what's desired.
推荐答案
在这里尝试一下.
所做的更改:
var i = -1;
$("#next").on("click", function(){
if(i <images.length - 1){
$("#result").children("p").remove();
i=i+1;
$("#result").append("<p>" +images[i] +"</p>");
}
})
$("#prev").on("click", function(){
if(i > 0){
$("#result").children("p").remove();
i=i-1;
$("#result").append("<p>" +images[i] +"</p>");
}
})
这篇关于为什么我要逐步遍历数组,而不能向后遍历?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文