【问题标题】:Uncaught TypeError: Cannot read property '2' of undefined未捕获的类型错误:无法读取未定义的属性“2”
【发布时间】:2015-04-04 09:20:53
【问题描述】:

以下是井字游戏程序的代码。我正在尝试编写 OO。我得到一个未捕获的类型错误:当我单击网格上的一个框时,无法读取 checkIfPositionIsTaken 函数中未定义的属性“2”。

以下是井字游戏对象的构造函数:

var TicTacToe = function () {

this.player1Name = "Player 1";
this.player2Name = "Player 2";
var turn = "";
var grid = [[0,0,0],[0,0,0],[0,0,0]];
var hasWinner = 0;
var moveCount = 0;
}

以下是 checkIfPositionIsTaken 函数。我相信错误出现在 this.grid 上,但它是在创建对象时定义的。

// Check If Position Is Taken
TicTacToe.prototype.checkIfPositionIsTaken = function(row, col){
   if(this.grid[row][col] !== 0){
      alert("This position is taken. Please try other position.");
      return true;
}
else{
    return false;
}
};

下面是我创建井字游戏对象的地方:

var theGame = new TicTacToe();

以下是我单击网格上的框的事件:

// Column click event
$(".col").click(function(){

    var row = $(this).parent().index();
    var col = $(this).index();

    if(theGame.checkIfPositionIsTaken(row, col) == false &&       theGame.checkIfGameHasEnded() == false){

if(theGame.turn == theGame.player1Name){

    $(this).text(theGame.drawO(row, col));

    if(theGame.winnerCheck(1,theGame.player1Name) == false && theGame.checkIfGameIsADraw() == false){
           theGame.turn = theGame.player2Name;
           theGame.setBoardMsg(theGame.player2Name+"'s turn now!");
        }
        return; 
    }
else{

    $(this).text(theGame.drawX(row, col));

    if(theGame.winnerCheck(2,theGame.player2Name) == false && theGame.checkIfGameIsADraw() == false){
           theGame.turn = theGame.player1Name;
           theGame.setBoardMsg(theGame.player1Name+"'s turn now!");
        }
        return; 
        }
}
});

这是我的第一个问题,如果您需要更多信息,请告诉我。谢谢。

【问题讨论】:

  • row 和 col 都设置为正确的值。将 row 和 col 插入 this.grid 时会抛出错误。 this.grid[row][col]

标签: javascript jquery


【解决方案1】:
var grid = [[0,0,0],[0,0,0],[0,0,0]];

gridTicTacToe 方法的“局部”变量,因此 this.grid 将是未定义的。

turnhasWinnermoveCount 也会遇到同样的问题。

【讨论】:

  • 那么我如何让它与 TicTacToe 作为对象一起工作?
  • 看看你对球员名字做了什么。
  • 谢谢。仍然是 JavaScript 新手,每天都在学习新东西。
猜你喜欢
  • 1970-01-01
  • 2021-12-22
  • 2015-01-06
  • 2017-07-26
  • 2019-02-26
  • 2021-12-25
  • 1970-01-01
相关资源
最近更新 更多