js將一維數組轉化爲二維數組

遇到的問題:後端

  後端返回的是一組一維數組,可是須要展現的格式是二維數組,常見的場景舉例:後臺返回10個長度的數組,須要分紅3個一組展現在banner上。數組

  例:[1,2,3,4,5,6,7,8,9,10]  =>  [[1,2,3], [4,5,6], [7,8,9], [10]]函數

解決方法及思路:spa

// 調用
let list = [1,2,3,4,5,6,7,8,9,10]
setTwoDimensionalArray(list);

// 轉化函數
function setTwoDimensionalArray (list) {
  const listResult = [];  // 最終返回的二維數組
  for (let i = 0; i < Math.ceil((list.length / 3)); i++) {
    listResult[i] = [];
    for (let j = 0; j < 3; j++) {
      // 若是是最後一個板塊
      if (i === (Math.ceil((list.length / 3)) - 1)) {
        if (Math.ceil((list.length % 3)) !== 0) {
          // 只有最後一個板塊的數據在餘數之內的才賦值
          if (j < Math.ceil((list.length % 3))) {
            listResult[i][j] = list[i * 3 + j];
          }
        } else {
          // 若是恰好整整一個板塊,則所有附上值
          listResult[i][j] = list[i * 3 + j];
        }
      } else {
        listResult[i][j] = list[i * 3 + j];
      }
    }
  }
  return listResult;
}
相關文章
相關標籤/搜索