0

I am trying to display images into thumbnails for my image gallery by using for...in loop but it is only able to display one image. I am still a beginner in javascript, so my understanding of for loops is still not good. Where did I go wrong?

sample array:

["http://tos-staging-web-server-s3.s3.amazonaws.com/9/catalogue/apples_in_season.png",
 "http://tos-staging-web-server-s3.s3.amazonaws.com/9/catalogue/apples_in_season.png"]

for...in loop:

for(var thumb in thumbnails) {
    $('.thumbnail img').attr({"src":[thumbnails[thumb]]});
}
David Hoelzer
  • 15,862
  • 4
  • 48
  • 67
zana
  • 259
  • 2
  • 4
  • 15
  • 1
    `thumb` is already the value, `$('.thumbnail img').attr({"src":thumb});` – Tushar Dec 08 '15 at 04:18
  • 4
    @Tushar: No, `thumb` is the key: `0`, then `1`. You need ES6 `for (var thumb of thumbnail)` for what you are saying. OP, `src` should not be an array: `attr({"src": thumbnails[thumb] })`. Also, you're setting *all* the thumbnail images to one value, then another, which is probably not what you want (then again, your whole array has the same value...) – Amadan Dec 08 '15 at 04:22
  • 1
    @Tushar it doesnt work i get a 404 error, isn't `thumb` the key? – zana Dec 08 '15 at 04:22
  • for-in should only be used for iterating over the keys and values of an object. Use a standard for loop or Array.prototype.forEach if you can use ES6. – wrshawn Dec 08 '15 at 04:29

2 Answers2

2

Actually, your loop is perfectly fine. You do iterate over all the URLs in your array, but for each URL you set it as src for the same thumbnail img, effectively overwriting it each time.

It is hard to help you fix it, because I don't know your exact layout and requirements, but you effectively either need to create a set of imgs for thumbnails (as opposed to just one img, which seems to be the case now), and set their srcs in order, or create brand new img each time and append it to some parent container, like so:

for(var thumb in thumbnails) {
    $(<some container>).append($('<img>').attr({"src":[thumbnails[thumb]]}));
}
Ishamael
  • 12,583
  • 4
  • 34
  • 52
2

You shouldn't use for .. in for iterating through arrays. Why?
Use Array.prototype.forEach instead.

Also, if you want to create an element using jQuery, then use another syntax:

thumbnails.forEach(function(thumb) {
    $("<img/>").attr('src', thumb).appendTo(container);
});

Working example:

var thumbnails = [
'https://blog.stackoverflow.com/images/wordpress/stackoverflow-logo-alt2-300.png', 
'http://letscode.ghost.io/content/images/2015/09/stackoverflow.png',
'https://i.stack.imgur.com/kq8EX.png'];

thumbnails.forEach(function(thumb) {
  $("<img/>").attr('src', thumb).appendTo('body');
});
img {
  height: 100px;
  width: auto;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Community
  • 1
  • 1
Yeldar Kurmangaliyev
  • 33,467
  • 12
  • 59
  • 101