侃侃无极
嵌套for循环可以解决这个问题。首先遍历所有行,然后遍历每一行的列。y将指示当前行和x当前列。检查第二个循环中的匹配项。如果找到匹配项,则返回对象中具有x和坐标的对象。yconst 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))
千巷猫影
简单的 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 lengthconst height = grid.lengthconst res = getXYCoords(8, grid);console.log(res, grid[res.x][res.y]) // verifies the resultsfunction 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)。