简体   繁体   English

二维网格如何找到给定节点号的索引

[英]2d grid how to find indices given node number

I created a 2d grid of divs with ids equal to the loop counter iteration.我创建了一个 2d 的 div 网格,其 id 等于循环计数器迭代。 When I click a div I want to use its id to determine its position on the grid.当我单击一个 div 时,我想使用它的 id 来确定它在网格上的位置。 So if I have a 4x4 grid and want the indices of the div with id=8 then the function would return 3,1 third row first column.因此,如果我有一个 4x4 网格并且想要 id=8 的 div 索引,那么该函数将返回 3,1 第三行第一列。 How do you write a function given the grid size and block number, then return its coordinates (row and column)给定网格大小和块号,如何编写函数,然后返回其坐标(行和列)

 const container = document.getElementById("container"); const N = 16; var blocks = new Array(N); function makeRows(rows, cols) { container.style.setProperty('--grid-rows', rows); container.style.setProperty('--grid-cols', cols); for (c = 0; c < (rows * cols); c++) { let cell = document.createElement("div"); cell.innerText = (c); cell.setAttribute("id",c); container.appendChild(cell).className = "grid-item"; } for (let i = 0; i <= N; i++) { blocks[i] = new Array(N); } let count = 0; for(let x=0; x<=15; x++){ for(let y=0; y<=15; y++){ blocks[x][y] = count; count++; } // for(let x=0; x<=15; x++){ for(let y=0; y<=15; y++){ console.log(blocks[x][y]); } } } } makeRows(N, N);
 :root { --grid-cols: 1; --grid-rows: 1; } #container { display: grid; grid-template-rows: repeat(var(--grid-rows), 1fr); grid-template-columns: repeat(var(--grid-cols), 1fr); } .grid-item { padding: 1em; border: 1px solid #ddd; text-align: center; }
 <html> <head> <link rel="stylesheet" href="style.css"> </head> <body> <div id="container"> </div> </body> <script src="astar.js"></script> </html>

A good way to deal with this is to instead of storing them in a 2D array, store them in one long array so you can access them immediately just by the ID -- assuming the ID matches the index in the array解决此问题的一个好方法是将它们存储在一个长数组中,而不是将它们存储在 2D 数组中,这样您就可以仅通过 ID 立即访问它们——假设 ID 与数组中的索引匹配

Then you want two functions: to turn an ID into an X,Y , and to turn an X,Y into an ID然后您需要两个函数:将ID转换为X,Y ,以及将X,Y转换为 ID

const width = 12

const positionToIndex = (x, y) => (y * width) + x

const indexToPosition = (index) => ({
  x: index % width,
  y: Math.floor(index / width)
})

This assumes the top left is (0,0) and the initial index is 0. Then you would just initialize it as a regular flat array, and use indextoPosition() to find the x,y position这假设左上角是 (0,0) 并且初始索引是 0。然后您只需将其初始化为常规平面数组,并使用indextoPosition()来查找 x,y 位置

// Initialize
for (var i = 0; i < width*height; i++) {
  const position = indexToPosition(i)
  blocks[i] = new Cell(position.x, position.y)
}

// When cell is clicked
cell.onclick = (id) => {
  const {x, y} = indextoposition(id)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM