简体   繁体   中英

Why does my Javascript loop only return the first value?

I'm creating a loop in ES6 which will be used to loop through and output a sequence of 51 images. I've created a for loop, however it only returns the first image, image_0000.jpg, when it runs.

How come it's not returning all 51 images?

sequenceImages() {
    for (let i = 0; i < 51; i++) {
      return <img src={require(`../images/image_000${i}.jpg`)} alt="" />

    }
  }

Your return statement exits the function immediately during the first time through the loop. It sounds like you want it to return many <img> tags so you can do something like this:

gitImage(i) {
  return <img src={require(`../images/image_000${i}.jpg`)} alt="" />
}
sequenceImages() {
  const images = [];
  for (let i = 0; i < 51; i++) {
    images.push(getImage(i));
  }
  return images;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM