网格如何在给定起始索引的情况下找到下一行的第一个位置的索引
Grid how to find the index of the first position of the next row given a starting index
0 1 2 3 4
5 6 7 8 9
10 11 12 13 14
假设有一个类似css网格的数组,有15个元素,有5列3行,起始索引为0
给定 任何 元素的索引,如何找到下一行中第一个位置的索引?
例如,
索引 4 returns 5
索引 6 returns 10
索引 2 returns 5
索引 11 returns 15
索引 0 returns 5
索引 14 returns 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];
};
0 1 2 3 4
5 6 7 8 9
10 11 12 13 14
假设有一个类似css网格的数组,有15个元素,有5列3行,起始索引为0
给定 任何 元素的索引,如何找到下一行中第一个位置的索引?
例如,
索引 4 returns 5
索引 6 returns 10
索引 2 returns 5
索引 11 returns 15
索引 0 returns 5
索引 14 returns 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];
};