无法获取索引,返回NaN

时间:2019-05-20 15:58:22

标签: javascript reactjs preact

我正在尝试在六边形网格中获取图块的邻居。 网格和图块都是React组件,我在Grid组件中有一个方便的方法来查找图块的所有邻居

该方法对于索引内的邻居很好用,并且我设置了一个模数以环绕到网格的另一侧(如果平铺要越界)。这些索引返回NaN。

  /**
   * Returns all neighbouring tiles of this tile
   */
  getTileNeighbours(tile) {
    // Checks all arrays in the two-dimensional grid if this tile exists
    for (let i in this.state.grid) {
      let array = this.state.grid[i]

      for (let j in array) {
        console.log("Looking...")
        let item = array[j]

        if (item.state.name === tile.state.name) {
          console.log("Found you!")
          // Gets the position of the tile
          let j = array.indexOf(tile)
          //console.log(`Tile was found at position [${i}, ${j}]. Returning neighbours.`)

          let neighbours = []
          // All possible permutations of neighbours
          let positions = [
            {i:0,j:-2}, {i:1,j:-1}, {i:1,j:1}, {i:0,j:2}, {i:-1,j:1}, {i:-1,j:-1}
          ]

          // If neighbouring indexes are out of bounds, wraps around to the other edge of the arrays
          for (let k in positions) {
            let position = positions[k]

            let xIndex = (i + position.i) % this.state.grid.length
            let yIndex = (j + position.j) % array.length
            console.log(`Resolving '(${i} + ${position.i}) % ${this.state.grid.length}': ${(i + position.i) % this.state.grid.length}`)
            console.log(`Actual indexes used: 'this.state.grid[${xIndex}][${yIndex}]'`)

            let match = this.state.grid[xIndex][yIndex]

            if (match) neighbours.push(match)
          }
          return neighbours
        }
      }
    }
  }

Here's a capture of my JavaScript console in Chrome

1 个答案:

答案 0 :(得分:0)

我弄清楚出了什么问题,这全都归结为变量类型,而不仅仅是数字。 i,j和k都是字符串(因为它们在for (x in y)上下文中使用),在k = 5时,我们以i + position.i等于0-1作为字符串,最终不能与模数一起使用。通过将ij强制为数字,我们将不再遇到NaN。 同样,使用模数来回绕也是一个坏主意。 当结果索引为负数时,已用三元数替换它以增加数组的长度 我只需要更改两行,就在这里

let xIndex = Number(i) + position.i < 0 ? Number(i) + position.i + this.state.grid.length : Number(i) + position.i
let yIndex = Number(j) + position.j < 0 ? Number(j) + position.j + array.length : Number(j) + position.j

这都是由于我完全缺乏关注,我应该更好地进行故障排除。