You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React棋盘开发:二维数组列索引获取不符合预期问题

React国际象棋棋盘行列索引异常问题解决方案

问题场景

我用React开发国际象棋棋盘,通过二维数组board存储棋盘格子的棋子状态:

let board = [
  ['rook', 'knight', 'bishop', 'queen', 'king', 'bishop', 'knight', 'rook'],
  ['pawn', 'pawn', 'pawn', 'pawn', 'pawn', 'pawn', 'pawn', 'pawn'],
  [null, null, null, null, null, null, null, null],
  [null, null, null, null, null, null, null, null],
  [null, null, null, null, null, null, null, null],
  [null, null, null, null, null, null, null, null],
  ['pawn', 'pawn', 'pawn', 'pawn', 'pawn', 'pawn', 'pawn', 'pawn'],
  ['rook', 'knight', 'bishop', 'queen', 'king', 'bishop', 'knight', 'rook'],
];

设计逻辑是通过格子存储棋子状态来实现移动,但点击格子打印行列索引时出现异常:

  • 第2至7行的列索引全部显示为0
  • 第1、8行前5个格子列索引正常,后续出现重复值

当前实现代码:

const Board = () => {

  //无关状态代码

  return (
    <div>
      <div className='board-cont'>
        {board.map((row) => {
          return row.map((col) => {
            return (
              <div
                className='board-sqr'
                onClick={() =>
                  console.log(
                    `Index of row ${board.indexOf(row)} 
                    \n Index of column ${row.indexOf(col)}`
                  )
                }
              >
                {col}
              </div>
            );
          });
        })}
      </div>
    </div>
  );
};

问题原因

你的猜测完全正确:indexOf()方法会返回第一个匹配值的索引。当数组中存在重复值(比如多行的pawn、重复的bishop/knight,以及大量null)时,它无法正确返回当前元素的实际索引。

比如第2行全是pawn,调用row.indexOf(col)时,只会返回第一个pawn的索引0;第3-6行全是null,同样只会返回0。

解决方案

直接使用map()方法提供的第二个参数(索引值),这是获取当前元素索引最可靠的方式:

修改后的代码:

const Board = () => {

  //无关状态代码

  return (
    <div>
      <div className='board-cont'>
        {board.map((row, rowIndex) => { // 直接获取行索引
          return row.map((col, colIndex) => { // 直接获取列索引
            return (
              <div
                className='board-sqr'
                onClick={() =>
                  console.log(
                    `Index of row ${rowIndex} 
                    \n Index of column ${colIndex}`
                  )
                }
              >
                {col}
              </div>
            );
          });
        })}
      </div>
    </div>
  );
};

这样就能准确获取每个格子对应的二维数组行列索引,完全避免indexOf()带来的重复值匹配问题。


内容的提问来源于stack exchange,提问作者Casey Cling

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.26 03:36:19