【问题标题】:Issue printing an array of images in javascript在 javascript 中打印图像数组的问题
【发布时间】:2017-08-17 08:25:12
【问题描述】:

我正在使用一组图像制作一个简单的画廊:

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'}
];

在这个容器内:

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

</div>

并使用函数将文本存储在使用地图的变量中:

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;
});

然后我使用 innerHTML 在我的 div 中打印它:

imageGallery.innerHTML=gallery;

我遇到的问题是,不知何故,每张图片之间都打印了一个昏迷“,”。这里的代码结果是 chrome:

这里是它在屏幕上的样子:

【问题讨论】:

  • 你能提供一个可行的例子吗?

标签: javascript html arrays iteration gallery


【解决方案1】:

您需要以其中没有逗号的方式连接数组。

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;

【讨论】:

    【解决方案2】:

    你想要的是每个或一个普通的 for 循环。

    您已将数组打印为 html。这就是它们看起来像数组元素的原因。

    https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/map

    map() 方法创建一个新数组,其结果是在调用数组中的每个元素上调用提供的函数。

    您将返回一个包含元素的数组。这就是您看到逗号的原因。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-24
      • 2018-08-29
      • 1970-01-01
      • 2011-11-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多