我有一个递归循环,对于这个问题,我已经简化为以下内容:
const move = (gameGrid) => {
if (Math.random() > 0.2) return false;
let newGameGrid = [...gameGrid];
return newGameGrid;
}
const play = (initGrid) => {
for (let player1Move=0; player1Move<9; player1Move++) {
grid1 = move(initGrid);
if (!grid1) continue;
for (let player2Move=0; player2Move<9; player2Move++) {
// Why is grid1 sometimes false here???
grid2 = move(grid1);
if (!grid2) continue;
play(grid2);
}
}
}
play([])
如果运行此程序,您会注意到,有时在第二个play()
循环中,对move(grid1)
的调用在[...gameGrid]
失败,因为grid1
为false。然而,这应该是不可能的,因为在第二个循环执行之前,grid1
被检查为假值。
你知道我在这里错过了什么吗?我猜grid1正在被覆盖,但我不确定如何覆盖或在哪里覆盖。
不确定您想要实现什么,但看起来您还没有在范围中定义 全局范围grid1
和grid2
,它们在递归函数调用期间在const move = (gameGrid) => {
if (Math.random() > 0.2) return false;
let newGameGrid = [...gameGrid];
return newGameGrid;
}
const play = (initGrid) => {
for (let player1Move = 0; player1Move < 9; player1Move++) {
let grid1 = move(initGrid);
if (!grid1) continue;
for (let player2Move = 0; player2Move < 9; player2Move++) {
// Why is grid1 sometimes false here???
let grid2 = move(grid1);
if (!grid2) continue;
play(grid2);
}
}
}
play([])