简体   繁体   English

JS/TS:二维字符串数组突然变得未定义时出错

[英]JS/TS: Error with 2D Array of strings suddenly becoming undefined

I'm making a Connect 4 game for a Discord.js application.我正在为 Discord.js 应用程序制作 Connect 4 游戏。 I'm keeping the game board as a 2D array of strings and initializing it like so:我将游戏板保留为 2D 字符串数组并像这样初始化它:

var board:string[][] = new Array<Array<string>>();
function resetBoard():void {
  for(let i=0; i<numRows; i++){
    board[i] = new Array<string>();
    for(let j=0; j<cols; j++){
      board[i].push(" ");
    }
  }
}

However, when I try to access a part of the board, it throws an error "cannot read property '0' of undefined".但是,当我尝试访问电路板的一部分时,它会引发错误“无法读取未定义的属性 '0'”。

function whatsAtPos(row, col){
  return board[row][col];
}

All of the functions are in the same file, and the board[][] is a global variable.所有函数都在同一个文件中,board[][] 是一个全局变量。 I've tried everything up my sleeve to fix it and I have no idea what's going on.我已经竭尽全力修复它,但我不知道发生了什么。

i suggest you to:我建议你:

  • verify you called resetBoard() before you called whatsAtPos在调用 whatsAtPos 之前验证您是否调用了 resetBoard()
  • validate that while reseting board 'numRows', 'cols' that you used will be const or not change before calling验证在重置板“numRows”时,您使用的“cols”将是 const 或在调用之前不会更改
  • add validation: to function whatsAtPos arguments about types, and during the function validate value of row, col that will be in range of [0, numRows-1], [0, cols-1]添加验证:到 function whatsAtPos arguments 关于类型,并在 function 验证行的值,列将在 [0,colsnum]-1 的范围内,

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

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