search

Home  >  Q&A  >  body text

javascript - Is only the last data output after the forEach loop?

As shown in the code, is the data generated after the foreach loop only the last one? My console.log(index); console can print out 0, 1, 2, 3, 4, but the pictures finally displayed on the page are all the pictures in case: 4.

 this.items.forEach((item:any) => {
                  // var index = this.items.indexOf(item);
                  // console.log(index);
                     // this.index.push(index);
                  switch (this.items.indexOf(item)){
                      case 0: this.imgSrc ='assets/liangshi.png';
                        break;
                      case 1: this.imgSrc ='assets/xiela.png';
                        break;
                      case 2: this.imgSrc ='assets/xuansuo.png';
                        break;
                      case 3: this.imgSrc ='assets/ganggou.png';
                        break;
                      case 4: this.imgSrc ='assets/gongqiao.png';
                        break;
                      default:
                        this.imgSrc = 'assets/ICON4TEST.png';
                  }
              });

This is the effect displayed on the page, all pictures are the last one

高洛峰高洛峰2749 days ago661

reply all(3)I'll reply

  • 世界只因有你

    世界只因有你2017-05-19 10:11:07

    You used the same variable to pass the image, and it must have been overwritten by gongqiao.png in the end.
    If you want to store a corresponding picture for each element in the array, you should use an array.

    reply
    0
  • 仅有的幸福

    仅有的幸福2017-05-19 10:11:07

    It may be because the last value of this.imgSrc is 4, and the previous value was not saved or subsequent operations were not performed

    reply
    0
  • 阿神

    阿神2017-05-19 10:11:07

    Don’t use this in javascript arrow functions
    Don’t use this in javascript arrow functions
    Don’t use this in javascript arrow functions

    reply
    0
  • Cancelreply