項目中遇到這樣一個需求:查詢到的數據中有一個字段是圖片的數組,但是在前段詳情頁面展示時,要求展示成下面的排版:
每行最多顯示3個圖片,所以每行都是遍歷輸出,每個單元格也是遍歷輸出的,但是數據圖片字段是單純的數組列表,沒法做到每三個元素就換行;所以最後,只能改變一下數組內的數據結構了,也就是將一維數組改造成二維數組:
一維數組:[a, b, c, d, e, f, g, ..... ]
二維數組:[[a, b, c], [d, e, f], [g, h, i] ....]
這樣子載遍歷的話,就可以了;
前端我用的是angular6,遍歷起來的話也是很方便的;
首先代碼中有着三個變量;
mydiary: any;
size = 3;
imgs: any[] = [];
mydiary對象中的momentAttachmentList字段是圖片數組;
size:每行顯示的個數;3個不夠的話還可以設置多一些;
imgs: 存放圖片的新數組
處理方法:
// 格式化圖片成九宮格
formartImgs(): void {
if (this.mydiary.momentAttachmentList && this.mydiary.momentAttachmentList.length > 0) {
for (let index = 0; index < this.mydiary.momentAttachmentList.length; index += this.size) {
const element = this.mydiary.momentAttachmentList[index];
this.imgs.push(this.mydiary.momentAttachmentList.slice(index, index + this.size));
}
}
}
前段頁面遍歷代碼:
<ion-grid>
<ion-row *ngFor="let imgsRow of imgs">
<ion-col col-4 col-sm *ngFor="let img of imgsRow">
<img [src]="img.thumbnailPhoto">
</ion-col>
</ion-row>
</ion-grid>