给定每行的项目和项目的总数,项目属于哪一列?

Given a total # of items and items per row, what column does an item belong to?

我有一个使用 CSS 网格的应用程序,它将包含可变数量的网格元素,尽管我会知道每一行中的项目数 - 是否有一种简单的方法来确定列数给定的项目?

即。给定 32 个元素,每行 8 行,元素编号 9 在第一列,元素编号 10 在第二列。

目前我正在这样做:

function getColumn(itemIndex, colsPerRow) {
  // its in the last column
  if (itemIndex % colsPerRow === 0) {
    return colsPerRow;
  }

  return itemIndex - (Math.floor(itemIndex/colsPerRow) * colsPerRow);
}

它 returns 是正确答案,但我觉得有更简单的方法可以解决这个问题。

考虑从 1 开始的编号:

column = (itemIndex - 1) % colsPerRow + 1 

if 子句中不需要)

您几乎已经找到答案了:项目编号模列数。

function getColumn(itemIndex, colsPerRow) {
  // its in the last column
  if (itemIndex % colsPerRow === 0) {
    return colsPerRow;
  }

  return itemIndex % colsPerRow;
}

console.log(
  getColumn(1,9),
  getColumn(2,9),
  getColumn(3,9),
  getColumn(4,9),
  getColumn(5,9),
  getColumn(6,9),
  getColumn(7,9),
  getColumn(8,9),
  getColumn(9,9),
  getColumn(10,9),
  getColumn(11,9)
);