[英]I'm trying to make sense of the React TicTacToe tutorial. How does their calculateWinner helper function operate?
[英]React tutorial function calculateWinner(squares) don't understand
我有這個問題,請在React教程頁面https://reactjs.org/tutorial/tutorial.html#declaring-a-winner中理解此代碼
function calculateWinner(squares) {
const lines = [
[0, 1, 2],
[3, 4, 5],
[6, 7, 8],
[0, 3, 6],
[1, 4, 7],
[2, 5, 8],
[0, 4, 8],
[2, 4, 6],
];
for (let i = 0; i < lines.length; i++) {
const [a, b, c] = lines[i];
if (squares[a] && squares[a] === squares[b] && squares[a] === squares[c]) {
return squares[a];
}
}
return null;
}
這條線
if (squares[a] && squares[a] === squares[b] && squares[a] === squares[c]) {
我不明白為什么不能
if (squares[a] === squares[b] && squares[a] === squares[c]) {
在原始代碼中有多余的平方[a]有什么好處?
如果沒有在if
條件的開始處設置squares[a]
,則在未定義squares[a]
情況下會出現js錯誤。
為簡單起見,我們具有以下條件:
if (a && a === b && a === c) {
它將首先檢查a
變量,如果未定義,則之后將不執行。
檢查squares [a]是否不為null,未定義,0,空字符串''和false,以便進一步檢查squares [a]。 如果squares [a]為null或undefined或false或0,則條件將返回false,並且由於“ &&”條件運算符,將不會進行進一步的檢查。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.