在此函数中,在第一个for循环之后,代码未到达。 alert("can't get here");
无效。{1}}我在这里错过了一些明显的JavaScript警告吗?
其余代码可以在这里找到:http://jsbin.com/tiweniludoqe/7/edit
非常感谢任何帮助。
function checkForWin(){
var winCondition = 0;
//check for horizontal wins
for(i = 0; i < board[i].length; i++) {
for(j = 0; j < board[i].length; j++) {
winCondition += board[i][j];
if(winCondition === board[i].length) {
alert("win detected horizontal");
}
}
winCondition = 0;
}
alert("can't get here");
//check for vertical wins
for(i = 0; i < board[i].length; i++) {
for(j = 0; j < board[i].length; j++) {
winCondition += board[j][i];
alert("winCondition: " + winCondition);
if(winCondition === board[i].length) {
alert("win detected horizontal");
}
}
}
//if diagonal / is 3 or -3 win
//if diagonal \ is 3 or -3 win
}
答案 0 :(得分:1)
我认为你的代码通过在第一个 for 循环中检查board [i] .length而陷入无限循环。
试试这个:
function checkForWin(){
var winCondition = 0;
//check for horizontal wins
for(i = 0; i < board.length; i++) { //HERE WE CHECK FOR board.length INSTEAD OF board[i].length
for(j = 0; j < board[i].length; j++) {
winCondition += board[i][j];
if(winCondition === board[i].length) {
alert("win detected horizontal");
}
}
winCondition = 0;
}
alert("can't get here");
//check for vertical wins
for(i = 0; i < board.length; i++) { //HERE YOU HAD THE SAME PROBLEM
for(j = 0; j < board[i].length; j++) {
winCondition += board[j][i];
alert("winCondition: " + winCondition);
if(winCondition === board[i].length) {
alert("win detected horizontal");
}
}
}
//if diagonal / is 3 or -3 win
//if diagonal \ is 3 or -3 win
}
最终推荐...当使用迭代循环时,尝试使用 var 来获取迭代变量,如下所示:
for(var i=0; i < board.length; i++)
而不是:
for(i=0; i < board.length; i++)
通过这样做,您可以避免使用这些变量填充全局范围(在 i 上面的情况下)。