數組分割成數組嵌套對象 (經常使用於分頁顯示數據)

  //模擬後臺調取到的數據
public datas: any = [
    {name: 1}, {name: 1}, {name: 1}, 
    {name: 2}, {name: 2}, {name: 2},
    {name: 3}, {name: 3}, {name: 3},
    {name: 4}, {name: 4}, {name: 4},
    {name: 5}, {name: 5}, {name: 5},
  ];  
  public pages: any = [];     //轉化爲對象存放在pages數組中

  rows(pagesNum) {
    //在原型上建立一個方法
    (Array as any).prototype.chunk = function (n) { 
      for (var i = 0, temp = [], l = ~~this.length / n; temp.length < l; temp[i++] = this.splice(0, n)) ;
      return temp;
    };                                                    
    //將獲取的數據轉化以後賦值給this.oages數組
    this.pages= this.datas.chunk(9);
    //-----------------------------------------------------
    //經過傳參將this.pages中下標(pagesNum)對應的對象內容打印出來
    let arr = this.pages[pagesNum];
    console.log(arr)
  }
相關文章
相關標籤/搜索