javascript - Is only the last data output after the forEach loop?
高洛峰
高洛峰 2017-05-19 10:09:07
0
3
691

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

高洛峰
高洛峰

拥有18年软件开发和IT教学经验。曾任多家上市公司技术总监、架构师、项目经理、高级软件工程师等职务。 网络人气名人讲师,...

reply all(3)
世界只因有你

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.

仅有的幸福

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

阿神

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

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template