网格如何找到给定起始索引的下一行第一个位置的索引


0  1  2  3  4
5  6  7  8  9
10 11 12 13 14

假设有一个像css网格一样的数组,上面有15个元素,有5列3行,起始索引为0

给定任何元素的索引,如何找到下一行第一个位置的索引?

例如

索引4返回5
index 6返回10
index2返回5
index 11返回15
index 0返回5
index 14返回15

我的公式是工作

const colPosition = index % colCount;
const rowPosition = Math.floor(index / colCount);
const answer = index + (colCount - colPosition) + 1;
const colPosition = index % colCount
const rowPosition = Math.floor( (index - colPosition) / colCount)
const answer = (rowPosition + 1) * colCount

我没有正确理解这个问题,但你可以试试这个

let arr = [
[0, 1, 2, 3, 4],
[5, 6, 7, 8, 9],
[10, 11, 12, 13, 14],
[15, 16, 17, 18, 19]
];
let a = value(7, arr);
console.log(a);
function value(index, array) {
let flat = array.flat();
let z = ((index + 1) / flat.length * array.length);
if (z > array.length) {
//return -1;
return (flat.slice().reverse()[0]) + 1;
}
if (z % 1 > 0) {
z = z - z % 1 + 1;
}
return array[z][0];
};

最新更新