【问题标题】:Incremental and Decremental of javascript arrayjavascript数组的增量和减量
【发布时间】:2021-06-07 14:08:36
【问题描述】:

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

【问题讨论】:

    标签: javascript angular ecmascript-6 angular-material array-indexing


    【解决方案1】:

    单击后您没有设置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];
      }
    

    【讨论】:

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

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

    像这样改变它:-

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

    this.imageIndex 越界时添加检查。

    【讨论】:

    • 当我第二次单击 next() 时,索引从 1 变为 3。它正在跳过索引 2
    猜你喜欢
    • 1970-01-01
    • 2012-03-27
    • 1970-01-01
    • 2017-04-07
    • 1970-01-01
    • 2019-08-02
    • 1970-01-01
    • 2020-03-14
    • 1970-01-01
    相关资源
    最近更新 更多