获取表中某个单元格的列索引和行索引

get column index and row index for a cell, in a table

本文关键字:索引 单元格 获取      更新时间:2023-09-26

在JS中,如何检索列&行索引;给定单元格索引和宽度(colCount)&表的高度(rowCount)?

例如。

var cellIndex = 11;
var colCount = 3;
var rowCount = 5;
| 1 | 2 | 3 |
| 4 | 5 | 6 |
| 7 | 8 | 9 |
|10 | X |12 |
|13 |14 |15 |
//should return
colIndex = 2;
rowIndex = 4;

例如。

var cellIndex = 8;
var colCount = 4;
var rowCount = 4;
| 1 | 2 | 3 | 4 |
| 5 | 6 | 7 | X |
| 9 |10 |11 |12 |
|13 |14 |15 |16 |
//should return
colIndex = 4;
rowIndex = 2;

谢谢!

指数的计算如下。

rowIndex = ( ( cellIndex - 1 ) / colCount ) + 1;
colIndex = ( ( cellIndex - 1 ) % colCount ) + 1;

注意,rowCount对于该计算不是必需的。