使用网格中的单元格编号获取 X 和 Y 坐标

http://img3.mukewang.com/64671cde00014e5d01770178.jpg

我有一个如上所示的网格,我想获取单元格的 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


}


慕盖茨4494581
浏览 139回答 2
2回答

侃侃无极

嵌套for循环可以解决这个问题。首先遍历所有行,然后遍历每一行的列。y将指示当前行和x当前列。检查第二个循环中的匹配项。如果找到匹配项,则返回对象中具有x和坐标的对象。yconst grid = [&nbsp; [1, 2, 3, 4, 5],&nbsp; [6, 7, 8, 9, 10],&nbsp; [11, 12, 13, 14, 15],&nbsp; [16, 17, 18, 19, 20],&nbsp; [21, 22, 23, 24, 25]];const rows = grid.length;&nbsp;const columns = grid[0].length;function getXYCoords(grid, cell) {&nbsp; for (let y = 0; y < rows; y++) {&nbsp; &nbsp; for (let x = 0; x < columns; x++) {&nbsp; &nbsp; &nbsp; if (grid[y][x] === cell) {&nbsp; &nbsp; &nbsp; &nbsp; return ({x, y});&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; }&nbsp; return null;}console.log(getXYCoords(grid, 8))console.log(getXYCoords(grid, 19))console.log(getXYCoords(grid, 22))

千巷猫影

简单的 2 循环解决方案会让你得到结果。const grid = [&nbsp; [1, 2, 3, 4, 5],&nbsp; [6, 7, 8, 9, 10],&nbsp; [11, 12, 13, 14, 15],&nbsp; [16, 17, 18, 19, 20],&nbsp; [21, 22, 23, 24, 25]]const width = grid[0].length //As my grid will always be regular, I just pick the first row's lengthconst height = grid.lengthconst res = getXYCoords(8, grid);console.log(res, grid[res.x][res.y]) // verifies the resultsfunction getXYCoords(cell, grid) {&nbsp; let x, y;&nbsp; for(x in grid) {&nbsp; &nbsp; for(y in grid[x]){&nbsp; &nbsp; &nbsp; if (grid[x][y] === cell) {&nbsp; &nbsp; &nbsp; &nbsp; return { x, y };&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; }}您还可以通过记忆函数来提高函数的性能,目前为 O(n^2)。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript