我正在使用以下代码迭代一些照片:
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,而不是最高索引,然后返回到最高索引。
if (this.lightboxIndex == 0) {
this.lightboxIndex = this.photos.length - 1;
} else {
this.lightboxIndex--;
}
您的 if
测试总是会成功,因此它只会不断减少索引,变成负数。
关于JavaScript 向后迭代项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38136850/