Aleix Gallet Segarra Aleix Gallet Segarra - 1 year ago 60
HTML Question

Issue printing an array of images in javascript

I'm doing a simple gallery using an array of images:

var gallery_pictures = [
{ name:'01.jpg', alt:'01'},
{ name:'02.jpg', alt:'01'},
{ name:'03.jpg', alt:'01'},
{ name:'04.jpg', alt:'01'},
{ name:'05.jpg', alt:'01'}
];


Inside this container:

<div style="width:1000px; margin: 0 auto;" id="gallery">

</div>


And using a function that store the text in a variable using a map:

var gallery = gallery_pictures.map(function gallery(foto, index, array) {
pictures = '<div style="width:190px;margin-right: 10px; float:left;"><img width="200" src="'+foto.name+'" alt="'+foto.alt+'" "></div>'
return pictures;
});


Then I print it in my div using innerHTML:

imageGallery.innerHTML=gallery;


The issue I have is that somehow there is a coma "," being printed between each picture. Here the code result in chrome:

like in the screenshoot

And here how it looks in the screen:
enter image description here

Answer Source

You need to concat array in a way there is no commas in it.

var gallery = "";
gallery_pictures.forEach(function(foto){
    var pictures = '<div style="width:190px;margin-right: 10px; float:left;"><img width="200" src="'+foto.name+'" alt="'+foto.alt+'" "></div>';
    gallery += pictures;
});
imageGallery.innerHTML = gallery;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download