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

标签 javascript html css math matrix

我创建了一个 2d 网格的 div,其 id 等于循环计数器迭代。当我单击一个 div 时,我想使用它的 id 来确定它在网格上的位置。因此,如果我有一个 4x4 网格并且想要 id=8 的 div 索引,那么该函数将返回 3,1 第三行第一列。如何编写给定网格大小和 block 编号的函数,然后返回其坐标(行和列)

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>

最佳答案

解决这个问题的一个好方法是将它们存储在一个长数组中,而不是将它们存储在一个 2D 数组中,这样您就可以仅通过 ID 立即访问它们 - 假设 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)
})

假设左上角为 (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)
}

关于javascript - 二维网格如何找到给定节点号的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60328780/

相关文章:

Javascript 在页面 Onsen UI 的推送页面中不起作用

javascript - PHP 项目的客户端验证是好是坏?以及如何完善PHP项目?

javascript - 数据库数组更新后 ng-repeat 不更新

jquery - 如何更改 li 最后一个 anchor 颜色

html - CSS 覆盖问题,在 Flash 元素上显示启动页面

javascript - 如何查找错误 : Cannot find module 的原因

javascript - jQueryUI DatePicker 自定义年份

html - 如何从 css 表格中删除边距和填充

html - 使用translateX代替margin-left的CSS动画,可能吗?

php - 错误网关 NGINX 502 PHP-FPM fastcgi