javascript数组的增量和减量

javascript数组的增量和减量,javascript,angular,ecmascript-6,angular-material,array-indexing,Javascript,Angular,Ecmascript 6,Angular Material,Array Indexing,我正在尝试使用角度材质创建简单的图像模型next()应该是从数组中查看下一个图像和prev()查看上一个图像 问题 下一个和上一个功能未按预期工作。如果单击next(),则索引仅增加+1,然后停止。如果我单击prev(),索引将变为-1 app.ts const imageArray = [ { imageData: [ 'https://via.placeholder.com/50', 'https://via.place

我正在尝试使用角度材质创建简单的图像模型
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>

下一个
以前的

问题在于,您实际上并没有增加/减少
这个.imageIndex
,而只是使用它的值,根据您的问题,最初它的值是0

这样改变它:-

  next() {
    this.currentImage = this.imageCollection[++this.imageIndex];
  }

  prev() {
    this.currentImage = this.imageCollection[--this.imageIndex];
  }

此.imageIndex
超出范围时,请添加检查。

问题在于,您实际上并没有增加/减少
此.imageIndex
,而只是使用它的值,最初根据您的问题,该值为0

这样改变它:-

  next() {
    this.currentImage = this.imageCollection[++this.imageIndex];
  }

  prev() {
    this.currentImage = this.imageCollection[--this.imageIndex];
  }

this.imageIndex
超出范围时,请添加检查。

单击后,您没有设置
this.imageIndex
。 试试这个:

next(){
//如果是最后一个图像,则转到第一个图像
如果(this.imageIndex==this.imageCollection.length-1)this.imageIndex=0;
否则这个.imageIndex++;
this.currentImage=this.imageCollection[this.imageIndex];
}
prev(){
//如果是第一个图像,则转到最后一个图像
如果(this.imageIndex==0)this.imageIndex=this.imageCollection.length-1;
否则,这个.imageIndex--;
this.currentImage=this.imageCollection[this.imageIndex];
}

单击后,您没有设置
此.imageIndex
。 试试这个:

next(){
//如果是最后一个图像,则转到第一个图像
如果(this.imageIndex==this.imageCollection.length-1)this.imageIndex=0;
否则这个.imageIndex++;
this.currentImage=this.imageCollection[this.imageIndex];
}
prev(){
//如果是第一个图像,则转到最后一个图像
如果(this.imageIndex==0)this.imageIndex=this.imageCollection.length-1;
否则,这个.imageIndex--;
this.currentImage=this.imageCollection[this.imageIndex];
}

当我第二次单击next()时,索引变为1到3。它正在跳过索引2@Johnny我怀疑这与这里提供的代码解决方案无关。当我第二次单击next()时,索引变为1到3。它正在跳过索引2@Johnny我怀疑这与这里提供的代码解决方案无关。当我第二次单击next()时,索引变为1到3。它跳过了索引2当我第二次单击next()时,索引变为1到3。它正在跳过索引2