Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/435.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 一种更干净的方式将物品放入网格和相邻的盒子中?_Javascript - Fatal编程技术网

Javascript 一种更干净的方式将物品放入网格和相邻的盒子中?

Javascript 一种更干净的方式将物品放入网格和相邻的盒子中?,javascript,Javascript,我有一个表示网格的数组数组。在本例中为2x3网格,网格的大小基于窗口的大小 let grid = [ [[], [], [],],//row [[], [], [],] //row ] 我想根据位置,在单元格和相邻单元格中放置对该的引用。这是我想出的最好的,但它已经感觉笨重了。什么是更干净的解决方案 getCell(pos, arr, type){ console.log(type, pos, arr.length) if(pos >= arr.length){

我有一个表示网格的数组数组。在本例中为2x3网格,网格的大小基于窗口的大小

let grid = [
  [[], [], [],],//row
  [[], [], [],] //row
]
我想根据位置,在单元格和相邻单元格中放置对该的引用。这是我想出的最好的,但它已经感觉笨重了。什么是更干净的解决方案

getCell(pos, arr, type){
  console.log(type, pos, arr.length)
  if(pos >= arr.length){
    return 0
  }
  if(pos < 0){
    return arr.length-1
  }
  return pos
}

setNearby(grid) {
  let col = Math.floor(this.position.y / grid.dimensions.height),
      row = Math.floor(this.position.x / grid.dimensions.width),
      offset = [-1, 0, 1];
  offset.forEach((rowOffset) => {
    offset.forEach((colOffset)=>{
      let pushRow = this.getCell(row+rowOffset, grid.grid)
      let pushCol = this.getCell(col+colOffset, grid.grid[pushRow])
      grid.grid[pushRow][pushCol].push(this)
    })
  })
}
getCell(位置、arr、类型){
控制台日志(类型、位置、排列长度)
如果(位置>=阵列长度){
返回0
}
如果(位置<0){
返回arr.length-1
}
返回位置
}
设置附近(网格){
设col=数学地板(该位置y/网格尺寸高度),
行=数学地板(此.position.x/网格.尺寸.宽度),
偏移量=[-1,0,1];
offset.forEach((rowOffset)=>{
offset.forEach((colOffset)=>{
设pushRow=this.getCell(行+行偏移量,grid.grid)
设pushCol=this.getCell(col+colOffset,grid.grid[pushRow])
grid.grid[pushRow][pushCol].push(此)
})
})
}

首先,如果您的解决方案可行,并且本文的目标是更干净/更高效的代码,那么codeReviews就是合适的平台。除此之外,你的问题有点不清楚。请解释你到底想实现什么?请你进一步澄清当你说“我想根据位置在单元格和相邻单元格中引用
这个
”时,你想做什么?css在哪里?@Omer:what css?@RashadSaleh基本上代码是做什么的,它将
推入单元和所有相邻单元。