首页 > 解决方案 > 如何修复此井字游戏的未捕获参考错误

问题描述

我正在做一个 HTML、CSS、JSS tictactoe 项目,我遇到了一个错误,当我尝试使用 console.log在我的文本编辑器中:


“未捕获的 ReferenceError:未定义 topLeft”
if (topLeft && topLeft === topMiddle && topLeft === topRight) {

我的代码:

             // HTML Elements
const statusDiv = document.querySelector('.status');
const resetDiv = document.querySelector('.reset');
const cellDivs = document.querySelectorAll('.game-cell');
//NEW querySelecterAll <= will grab every occurrence put in ('') 
//Grabbing statusDiv to manipulate it (change when it'll x or o's turn)

            //Game Variables
let gameIsLive = true; 
//statement would be false if someone won/ game ended 
let xIsNext = true; 
//meaning if it's T = x's turn, if it's F = O's turn

           // Functions
const checkGameStatus = () => {
const topLeft = cellDivs[0].classList[2];
const topMiddle = cellDivs[1].classList[2];
const topRight = cellDivs[2].classList[2];
const middleLeft = cellDivs[3].classList[2];
const middleMiddle = cellDivs[4].classList[2];
const middleRight = cellDivs[5].classList[2];
const bottomLeft = cellDivs[6].classList[2];
const bottomMiddle = cellDivs[7].classList[2];
const bottomRight = cellDivs[8].classList[2];
}

           // Check Winner
if (topLeft && topLeft === topMiddle && topLeft === topRight) { 
console.log(topLeft);
}

我所做的代码似乎与视频相同,所以我不确定为什么会收到此错误。

参考

教程中的人有他自己的 GitHub,代码在这里输入链接描述

这将是我目前的流程在此处输入链接描述

我之前发布了一个类似的问题,这是我第一次解决问题。有点担心它可能会再次关闭,所以请让我知道我做错了问题的哪一部分。

标签: javascripthtmlundefinedtic-tac-toeuncaught-reference-error

解决方案


您的问题是块范围。你在这个块中声明你的变量:

const checkGameStatus = () => {
  const topLeft = cellDivs[0].classList[2];
  [...]
}

但是随后您尝试访问块外不存在的变量。

相反,初始化块外的变量,然后分配值:

let topLeft;

const checkGameStatus = () => {
  topLeft = cellDivs[0].classList[2];
  [...]
}

checkGameStatus()

if (topLeft && topLeft === topMiddle && topLeft === topRight) { 
  console.log(topLeft);
}

推荐阅读