2 回答
TA贡献2051条经验 获得超10个赞
嵌套for循环可以解决这个问题。首先遍历所有行,然后遍历每一行的列。y将指示当前行和x当前列。
检查第二个循环中的匹配项。如果找到匹配项,则返回对象中具有x和坐标的对象。y
const grid = [
[1, 2, 3, 4, 5],
[6, 7, 8, 9, 10],
[11, 12, 13, 14, 15],
[16, 17, 18, 19, 20],
[21, 22, 23, 24, 25]
];
const rows = grid.length;
const columns = grid[0].length;
function getXYCoords(grid, cell) {
for (let y = 0; y < rows; y++) {
for (let x = 0; x < columns; x++) {
if (grid[y][x] === cell) {
return ({x, y});
}
}
}
return null;
}
console.log(getXYCoords(grid, 8))
console.log(getXYCoords(grid, 19))
console.log(getXYCoords(grid, 22))
TA贡献1829条经验 获得超7个赞
简单的 2 循环解决方案会让你得到结果。
const grid = [
[1, 2, 3, 4, 5],
[6, 7, 8, 9, 10],
[11, 12, 13, 14, 15],
[16, 17, 18, 19, 20],
[21, 22, 23, 24, 25]
]
const width = grid[0].length //As my grid will always be regular, I just pick the first row's length
const height = grid.length
const res = getXYCoords(8, grid);
console.log(res, grid[res.x][res.y]) // verifies the results
function getXYCoords(cell, grid) {
let x, y;
for(x in grid) {
for(y in grid[x]){
if (grid[x][y] === cell) {
return { x, y };
}
}
}
}
您还可以通过记忆函数来提高函数的性能,目前为 O(n^2)。
添加回答
举报