如何解决javascript数组的增量和减量
我正在尝试使用角材料创建简单的图像模态。 next()
应该是查看数组中的下一张图片,prev()
查看上一张图片。
问题 next 和 prev 功能未按预期工作。如果单击 next() 索引仅增加 +1,则停止。如果我点击 prev() 索引变为 -1
app.ts
const imageArray = [
{
imageData: [
'https://via.placeholder.com/50','https://via.placeholder.com/60'
],},{
imageData: [
'https://via.placeholder.com/100'
],{
imageData: [
'https://via.placeholder.com/150'
],}
];
next() {
this.currentimage = this.imageCollection[this.imageIndex + 1];
}
prev() {
this.currentimage = this.imageCollection[this.imageIndex - 1];
}
processImage() {
const rawData = this.imageArray;
this.imageCollection = rawData.flatMap((el: any) => el.imageData);
this.imageIndex = this.imageCollection.findindex((x) => x === this.data.selectedImage);
this.currentimage = this.imageCollection[this.imageIndex];
}
app.html
<img [src]="currentimage"
alt="customer document" />
<div (click)="next()">next</div>
<div (click)="prev()">prevIoUs</div>
解决方法
问题在于您实际上并没有增加/减少 this.imageIndex
,而只是使用它的值,根据您的问题最初为 0。
像这样改变它:-
next() {
this.currentImage = this.imageCollection[++this.imageIndex];
}
prev() {
this.currentImage = this.imageCollection[--this.imageIndex];
}
当 this.imageIndex
越界时添加检查。
您没有在点击后设置 this.imageIndex
。
试试这个:
next() {
// if is last image,then go to first image
if(this.imageIndex === this.imageCollection.length - 1) this.imageIndex = 0;
else this.imageIndex++;
this.currentImage = this.imageCollection[this.imageIndex];
}
prev() {
// if is first image,then go to last image
if(this.imageIndex === 0) this.imageIndex = this.imageCollection.length - 1;
else this.imageIndex--;
this.currentImage = this.imageCollection[this.imageIndex];
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。