window.TicTacToet.compMove = function (row, col) {
var player = window.TicTacToet.PlayerTurn;
var board = window.TicTacToet.Board;
for (i = 0; i < window.TicTacToet.Board.length; i++) {
for (j = 0; j < window.TicTacToet.Board[i].length; j++) {
if (window.TicTacToet.Board[i][j] == null) {
getWin(row, col, player, board);
} else {
console.log("position occupied");
}
}
}
}
function getWin($r, $c, $player, $board) {
checkTop($r, $c, $player, $board);
}
function checkTop($x, $y, $player, b) {
console.log("ENTER");
var success = false;
for (i = 0; i < 3; i++) {
$x--;
if ($x < 0) {
return success;
}
if (b[$y][$x] != $player) {
return success;
}
}
success = true;
return success;
}
Run Code Online (Sandbox Code Playgroud)
函数check-Top执行无限次.参数row和col是表的坐标.播放器将返回true或false,并且板是具有9个元素的数组.window.TicTacToet.Board.length和window.TicTacToet.Board [i] .length都有值9,即9 x 9.控制台.log("ENTER")应该执行91次但是它执行的次数是无限的.是这个的原因.因为这一切所有其他功能都不能正常工作,游戏本身不会播放.请帮帮忙.这是9 x 9可点击的棋盘游戏.
我想你可能想要使用var关键字作为变量i,因为你i在两个for循环中使用相同的变量名.因此,在第二个for循环中,您无意中覆盖i了第一个for循环.为避免这种情况,您可以使用var关键字声明变量,该关键字定义 变量范围.
更改
for(i=0;i<window.TicTacToet.Board.length;i++)
Run Code Online (Sandbox Code Playgroud)
至
for(var i=0;i<window.TicTacToet.Board.length;i++)
Run Code Online (Sandbox Code Playgroud)
并改变
for (i=0;i<3;i++)
Run Code Online (Sandbox Code Playgroud)
至
for (var i=0;i<3;i++)
Run Code Online (Sandbox Code Playgroud)
没有var关键字.
i = 100;
function foo(){
i = 0; // overwriting i to 0
}
foo();
alert(i); // shows 0
Run Code Online (Sandbox Code Playgroud)
用var关键字.
var i = 100;
function foo(){
var i = 0; // This defines a new variable 'i' in the scope of function foo(){}.
}
foo();
alert(i); // shows 100
Run Code Online (Sandbox Code Playgroud)
使用var关键字(在嵌套函数中)
var i = 100;
function foo(){
var i = 200; // A new variable 'i' in the scope of function foo(){}.
function bar(){
var i = 0;// A new variable 'i' in the scope of function bar(){}.
}
bar();
alert(i); // shows 200
}
foo();
alert(i); //shows 100
Run Code Online (Sandbox Code Playgroud)
在大多数具有块级变量范围的语言中,变量可以在用大括号({和})包围的块中访问.但是JavaSciprt不会在块的末尾终止作用域,而是在函数结束时终止它们.
我相信有很多关于它的文章和文件.我用Google搜索并发现了一篇引人入胜的介绍性文章. http://javascriptissexy.com/javascript-variable-scope-and-hoisting-explained/
希望这可以帮助.