我正在使用以下代码迭代一些照片:
if (this.lightboxIndex < this.photos.length - 1) {
this.lightboxIndex++;
} else {
this.lightboxIndex = 0;
}
this.lightboxSrc = this.photos[this.lightboxIndex].src;
},
我如何在相同的照片中向后迭代?这是否符合我的需要?
if(this.lightboxIndex < this.photos.length - 1){
this.lightboxIndex--;
} else {
this.lightboxIndex = 0;
}
this.lightboxSrc = this.photos[this.lightboxIndex].src;
},
答案 0 :(得分:2)
当您向下迭代时,您需要检查是否达到0,而不是最高索引,然后返回到最高索引。
if (this.lightboxIndex == 0) {
this.lightboxIndex = this.photos.length - 1;
} else {
this.lightboxIndex--;
}
您的if
测试将始终成功,因此它将继续递减索引,进入负数。
答案 1 :(得分:0)
if(this.lightboxIndex > 0) {
this.lightboxIndex--;
} else {
this.lightboxIndex = this.photos.length - 1;
}
this.lightboxSrc = this.photos[this.lightboxIndex].src;
答案 2 :(得分:0)
为什么不使用递减的created_at
循环?
for
答案 3 :(得分:0)
让我们向后思考来自last to first
,所以如果它是first index
,则分配到最后一个索引,否则减少到第一个索引!
转发将从first to last
开始,如果是last index
,则转回first index
,否则会增加到最后一个索引!
this.lightboxIndex = 0;
this.photos = ['a','b','c'];
function forward(){
if (this.lightboxIndex == this.photos.length -1) {
this.lightboxIndex = 0;
} else {
this.lightboxIndex++;
}
this.lightboxSrc = this.photos[this.lightboxIndex];
console.log(this.lightboxSrc);
}
function backward () {
if(this.lightboxIndex == 0) {
this.lightboxIndex = this.photos.length -1;
}
else {
this.lightboxIndex--;
}
this.lightboxSrc = this.photos[this.lightboxIndex];
console.log(this.lightboxSrc);
}
forward();
forward();
forward();
backward();
backward();
backward();