无法使用 for-in javascript 进行迭代

Cannot iterate using for-in javascript

我正在尝试使用 for...in 循环将图像显示为我的图库的缩略图,但它只能显示一张图像。我还是javascript的初学者,所以对for循环的理解还不是很好。我哪里错了?

示例数组:

["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 循环:

for(var thumb in thumbnails) {
    $('.thumbnail img').attr({"src":[thumbnails[thumb]]});
}

实际上,您的循环非常好。您确实遍历了数组中的所有 URL,但是对于每个 URL,您将其设置为 src 以用于相同的缩略图 img,每次都有效地覆盖它。

很难帮你修复它,因为我不知道你的确切布局和要求,但你实际上需要为缩略图创建一组 img(而不是只创建一个) img,现在似乎是这种情况),并按顺序设置它们的 src,或者每次都创建全新的 img 并将其附加到某个父容器,如下所示:

for(var thumb in thumbnails) {
    $(<some container>).append($('<img>').attr({"src":[thumbnails[thumb]]}));
}

您不应该使用 for .. in 遍历数组。 Why?
请改用 Array.prototype.forEach

此外,如果您想使用 jQuery 创建元素,请使用另一种语法:

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

工作示例:

var thumbnails = [
'https://blog.whosebug.com/images/wordpress/Whosebug-logo-alt2-300.png', 
'http://letscode.ghost.io/content/images/2015/09/Whosebug.png',
'http://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>