美文网首页
js将数组对象分割成组,slice使用

js将数组对象分割成组,slice使用

作者: 亻火子 | 来源:发表于2020-01-22 10:36 被阅读0次

将数组内容分组输出

下面是微信朋友圈图片展示效果事例代码:

var images= [
  {source :'source.jpg',thumb :'thumb.jpg'},
  {source :'source.jpg',thumb :'thumb.jpg'},
  {source :'source.jpg',thumb :'thumb.jpg'},
  {source :'source.jpg',thumb :'thumb.jpg'},
  {source :'source.jpg',thumb :'thumb.jpg'},
  {source :'source.jpg',thumb :'thumb.jpg'},
  {source :'source.jpg',thumb :'thumb.jpg'},
  {source :'source.jpg',thumb :'thumb.jpg'},
  {source :'source.jpg',thumb :'thumb.jpg'}
];
var html = '';
switch (images.length) {
  case 1:
    html += '<div class="weui-flex">' +
    '<div class="weui-flex__item" style="flex: 2">' +
    '  <img class="weui-media-box__thumb" data-source="' + images[0].source + '" src="' + images[0].source + '">' +
    '</div>' +
    '<div class="weui-flex__item"></div></div>';
    break;
  case 2:
    html += '<div class="weui-flex">' +
      '<div class="weui-flex__item">' +
      '  <img class="weui-media-box__thumb" data-source="' + images[0].source + '" src="' + images[0].thumb + '">' +
      '</div>' +
      '<div class="weui-flex__item">' +
      '  <img class="weui-media-box__thumb" data-source="' + images[1].source + '" src="' + images[1].thumb + '">' +
      '</div>' +
      '<div class="weui-flex__item"></div></div>';
    break;
  case 4:
    html += '<div class="weui-flex">' +
      '<div class="weui-flex__item">' +
      '  <img class="weui-media-box__thumb" data-source="' + images[0].source + '" src="' + images[0].thumb + '">' +
      '</div>' +
      '<div class="weui-flex__item">' +
      '  <img class="weui-media-box__thumb" data-source="' + images[1].source + '" src="' + images[1].thumb + '">' +
      '</div>' +
      '<div class="weui-flex__item"></div></div>' +
      '<div class="weui-flex">' +
      '<div class="weui-flex__item">' +
      '  <img class="weui-media-box__thumb" data-source="' + images[2].source + '" src="' + images[2].thumb + '">' +
      '</div>' +
      '<div class="weui-flex__item">' +
      '  <img class="weui-media-box__thumb" data-source="' + images[3].source + '" src="' + images[3].thumb + '">' +
      '</div>' +
      '<div class="weui-flex__item"></div></div>';
    break;
  default:
    if (images.length > 0) {
      for (var i = 0; i < images.length; i += 3) {
        html += '<div class="weui-flex">';
        var image = images.slice(i, i + 3);
        for (var j = 0; j < 3; j++) {
          if (image[j]) html += '<div class="weui-flex__item"><img class="weui-media-box__thumb" data-source="' + images[j].source + '" src="' + image[j].thumb + '"></div>';
          else html += '<div class="weui-flex__item"></div>';
        }
        html += '</div>';
      }
    }
}

相关文章

网友评论

      本文标题:js将数组对象分割成组,slice使用

      本文链接:https://www.haomeiwen.com/subject/ivuuzctx.html