問題描述
如何修復此井字遊戲的未捕獲參考錯誤 (How do I fix an uncaught reference error for this TicTacToe)
我正在做一個 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
教程中的人有自己的GitHub,代碼在此處輸入鏈接描述
我之前發布了一個類似的問題,這是我第一次解決問題。有點擔心它可能會再次關閉,所以請讓我知道我做錯了問題的哪一部分。
- Youtube
這將是我目前的流程 在此處輸入鏈接描述
我之前發布了一個類似的問題,這是我第一次解決問題。有點擔心它可能會再次關閉,所以請讓我知道我做錯了問題的哪一部分。
我之前發布了一個類似的問題,這是我第一次解決問題。有點擔心它可能會再次關閉,所以請讓我知道我做錯了問題的哪一部分。 我之前發布了一個類似的問題,這是我第一次解決問題。有點擔心它可能會再次關閉,所以請讓我知道我做錯了問題的哪一部分。參考解法
方法 1:
Your issue is with block scoping. You're declaring your variables inside this block:
const checkGameStatus = () => {
const topLeft = cellDivs[0].classList[2];
[...]
}
But then you're trying to access the variables outside the block, where they don't exist.
Instead, initialize the variables outside the block, and then assign the values:
let topLeft;
const checkGameStatus = () => {
topLeft = cellDivs[0].classList[2];
[...]
}
checkGameStatus()
if (topLeft && topLeft === topMiddle && topLeft === topRight) {
console.log(topLeft);
}
(by KO‑d14、selfagency)