javascript - 使用网格中的单元格编号获取 X 和 Y 坐标
问题描述
我有一个如上所示的网格,我想获取单元格 x 和 y 坐标及其编号。
例如:单元格编号 18 => x = 3, y = 4
我已经拥有的:
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
console.log(getXYCoords(8, grid))
function getXYCoords(cell, grid) {
//This is where I can't figure out how to do it
}
解决方案
简单的 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)。
推荐阅读
- vue.js - Vue 3 - 通过 $router 将查询字符串参数添加到 URL
- php - 未检索或存储隐藏的表单值
- php - htaccess 重写规则删除子目录和 .php 扩展名
- android - 带有操作按钮和图像的 Flutter 本地通知
- docker - 无法通过 docker-sdk golang 连接到 Docker 守护进程
- vb.net - SQLCMD 不通过 asp.net 应用程序执行
- wpf - Prism 库 - 在视图中获取范围区域
- swiftui - SwiftUI:使用 ListView 的替代方案?
- c# - 可空数组表示法
- chrome-ux-report - 查询 CrUX 报告 API 时以随机顺序响应的指标