React实战教程:井字棋calculateWinner函数比较逻辑解惑
calculateWinner Function's Comparison Logic Hey there! Let's walk through exactly how the comparison logic in this Tic-Tac-Toe winner-checker works. I'll break it down piece by piece so it makes total sense.
First, What's the lines Array?
The lines array holds every possible winning combination of square indices in a 3x3 Tic-Tac-Toe board. Each sub-array represents three squares that form a winning line:
- Horizontal lines:
[0,1,2],[3,4,5],[6,7,8] - Vertical lines:
[0,3,6],[1,4,7],[2,5,8] - Diagonal lines:
[0,4,8],[2,4,6]
The Loop: Checking Each Winning Line
The for loop runs through every entry in the lines array. For each line, we use destructuring to grab the three indices:
const [a, b, c] = lines[i];
So if we're on the first iteration (i=0), a=0, b=1, c=2—the top row of the board.
The Critical Comparison Logic
Now let's unpack the if condition:
if (squares[a] && squares[a] === squares[b] && squares[a] === squares[c]) { return squares[a]; }
This has three key parts, checked in order:
squares[a]: First, we make sure the first square in the line isn't empty. In the game, empty squares are usuallynullorundefined, so this check skips any lines where the first square hasn't been played yet.squares[a] === squares[b]: We check if the first square's value (either'X'or'O') matches the second square's value.squares[a] === squares[c]: We check if the first square's value also matches the third square's value.
If all three conditions are true, that means all three squares in the line are the same non-empty value—so that player has won! We immediately return that value ('X' or 'O') as the winner.
What If No Winner?
If the loop finishes checking all 8 winning lines and none of them meet the condition, the function returns null—meaning no one has won yet, and the game can continue.
Example Walkthrough
Let's say the squares array looks like this:
['X', 'X', 'X', null, 'O', null, null, 'O', null]
When the loop hits the first line ([0,1,2]):
squares[a]is'X'(not empty, so first condition passes)squares[a] === squares[b]→'X' === 'X'(passes)squares[a] === squares[c]→'X' === 'X'(passes)
The function will immediately return'X'—we found our winner!
内容的提问来源于stack exchange,提问作者Alon Joshua

