javascript 未捕获的类型错误:无法读取未定义的属性“2”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28328401/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Uncaught TypeError: Cannot read property '2' of undefined
提问by b2norma
The following is code for a TicTacToe program. I'm trying to write OO. I'm getting a Uncaught TypeError: Cannot read property '2' of undefined in the checkIfPositionIsTaken function when I click a box on my grid.
以下是井字游戏程序的代码。我正在尝试编写 OO。当我单击网格上的一个框时,我收到 Uncaught TypeError: Cannot read property '2' of undefined in the checkIfPositionIsTaken 函数。
The following is the constructor for the TicTacToe Object:
以下是井字游戏对象的构造函数:
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;
}
The following is the checkIfPositionIsTaken function. I believe the error is on this.grid but it is defined when the object is created.
下面是 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;
}
};
The following is where I create the TicTacToe object:
下面是我创建井字游戏对象的地方:
var theGame = new TicTacToe();
The following is my event for clicking a box on my grid:
以下是我单击网格上的框的事件:
// 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;
}
}
});
This is my first question so just let me know if you need more information. Thanks.
这是我的第一个问题,所以如果您需要更多信息,请告诉我。谢谢。
采纳答案by epascarello
var grid = [[0,0,0],[0,0,0],[0,0,0]];
grid
is a "local" variable to the TicTacToe
method so this.grid
is going to be undefined.
grid
是该TicTacToe
方法的“本地”变量,因此this.grid
将是未定义的。
You are going to have the same problems with turn
, hasWinner
, moveCount
.
您将遇到与turn
, hasWinner
,相同的问题moveCount
。